Swift/UISwitch: how to implement a delegate/listener

后端 未结 7 1656
慢半拍i
慢半拍i 2020-12-29 19:24

In my UITableViewController I have a custom cell which contains a switcher which is the following:

import Foundation
import UIKit

class SwitchCell: UITableV         


        
7条回答
  •  伪装坚强ぢ
    2020-12-29 20:04

    I have the solution in objective-c, it is the method that I use regularly:

    -The Action of the switch must be in tableviewcontroller and not on the cell

    -When You tap on the switch inside the action can do this to find the correct cell, then you can easily find the index or any other value that you need ...

    - (IBAction)switchValueChanged:(UISwitch *)sender
    {
        YourCellClass *cell = (YourCellClass *)[sender findSuperViewWithClass:[YourCellClass class]];
            etc....
        }
    

    the method findSuperviewWithClass is a category on UIView

    - (UIView *)findSuperViewWithClass:(Class)superViewClass
    {
        UIView *superView = self.superview;
        UIView *foundSuperView = nil;
    
        while (nil != superView && nil == foundSuperView)
        {
            if ([superView isKindOfClass:superViewClass])
            {
                foundSuperView = superView;
            } else
            {
                superView = superView.superview;
            }
        }
        return foundSuperView;
    }
    

提交回复
热议问题