本文介绍了Swift/UISwitch:如何实现委托/侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在UITableViewController中,我有一个自定义单元格,其中包含一个切换器,如下所示:
In my UITableViewController I have a custom cell which contains a switcher which is the following:
import Foundation
import UIKit
class SwitchCell: UITableViewCell {
@IBOutlet weak var label : UILabel!
@IBOutlet weak var switchEmail : UISwitch!
func setEditable(canEdit:Bool) {
if (canEdit) {
self.switchEmail.enabled = true
self.label.highlighted = false
}
else {
self.switchEmail.enabled = false
self.label.highlighted = true
}
}
func configureCellWithSwitch(labelText:String, switchValue:Bool, enabled:Bool) {
var labelFrame:CGRect = self.label.frame
labelFrame.size.height = Settings.labelHeight
self.label.frame = labelFrame
self.label.text = labelText
if (switchValue) {
self.switchEmail.setOn(true, animated: true)
}
else {
self.switchEmail.setOn(false, animated: true)
}
self.setEditable(enabled)
}
}
我想知道如何实现对切换器的侦听器/代理,以便从UITableViewController获得其值.我能够使用实现方法的UITextField和UITextView为单元格编写委托/侦听器
I would like to know how to implement a listener/delegate to the switcher in order to get its value from the UITableViewController. I was able to write delegate/listeners for a cell with UITextField and UITextView implementing the methods
func controller(controller: UITableViewCell, textViewDidEndEditing: String, atIndex: Int)
和
func controller(controller: UITableViewCell, textFieldDidEndEditingWithText: String, atIndex: Int)
但是我不知道我应该实现什么切换器.
but I don't know what I should implement the switcher.
推荐答案
UISwitch
没有委托协议.您可以听以下状态:
UISwitch
has no delegate protocol. You can listen to the status as follows:
ObjC:
// somewhere in your setup:
[self.mySwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
- (void)switchChanged:(UISwitch *)sender {
// Do something
BOOL value = sender.on;
}
迅速:
mySwitch.addTarget(self, action: "switchChanged:", forControlEvents: UIControlEvents.ValueChanged)
func switchChanged(mySwitch: UISwitch) {
let value = mySwitch.on
// Do something
}
Swift3:
mySwitch.addTarget(self, action: #selector(switchChanged), for: UIControlEvents.valueChanged)
func switchChanged(mySwitch: UISwitch) {
let value = mySwitch.isOn
// Do something
}
Swift4:
mySwitch.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
@objc func switchChanged(mySwitch: UISwitch) {
let value = mySwitch.isOn
// Do something
}
这篇关于Swift/UISwitch:如何实现委托/侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!