swift - 当用户来到 Controller 时如何存储开关值

标签 swift

我有一个带有一个标签和开关的自定义单元格,我想存储当用户访问该 Controller 时打开或关闭的那个开关的值。

var point = Int()
func cellButtonTapped(sender: UISwitch) {
    let pointInTable: CGPoint = sender.convertPoint(sender.bounds.origin, toView: self.tableView)
    let cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
    print(cellIndexPath)
    point = cellIndexPath!.row
    print(point)
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "setting"
    let cell =  (self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier)) as? SettingCell
    if(indexPath.section==0)
    {
     let str = options1[indexPath.row]
        cell?.label.text=str
        cell?.delegate=self
        return cell!
    }
    else if(indexPath.section==1){
        let str = options1[indexPath.row]
        cell?.label.text=str
        cell?.delegate=self
        return cell!
    }
    return UITableViewCell();
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if(section==0)
    {
        return options1.count;
    }
    else{
        return options2.count;
    }
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 2;
}

C自定义单元格:

protocol MyInfo {
    func cellButtonTapped(sender: UISwitch)
}
class SettingCell: UITableViewCell {
    var delegate:MyInfo?

    @IBAction func buttonTapped(sender: AnyObject) {
        delegate?.cellButtonTapped(self.switchButton)
        //print("hiii")
    }

    @IBOutlet weak var switchButton: UISwitch!
    @IBOutlet weak var label: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

最佳答案

例如,您需要像这样向您的 UISwitch 添加一个目标

switch.addTarget(self, action: Selector("stateChanged:"), forControlEvents: UIControlEvents.ValueChanged)

其中 stateChanged 是将在触发事件时调用的方法的名称(当 UISwitch 值更改时)。然后您需要添加实际的 stateChanged 方法,该方法会将值保存在 NSUserDefaults

func stateChanged(switch: UISwitch) {
    NSUserDefaults.standardUserDefaults().setBool(switch.on, forKey: "settings")
    //The key could be another string.
}

关于swift - 当用户来到 Controller 时如何存储开关值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34307394/

相关文章:

json - 如何在 Alamofire 请求 swift 3 上发出警报

operators - swift 1.2 ??运算符(operator)

ios - UIWebview.loadURL() 但 URL 是自签名证书。 swift iOS

ios - Xcode Swift 自动完成失败<<错误类型>>

ios - 将图像从一个 VC 传输到另一个不工作

arrays - 通过从另一个数组排序来对 Swift 数组进行排序

ios - 如何使用 Swift 创建自定义类加载 View

swift - 使用 DateComponents 创建日期

swift - 无返回值

iOS 录音机在 swift 上的可视化