Dan*_*ieu 4 iphone uitableview uiswitch ios swift
这个问题已经走近这里在Objective-C.但我在斯威夫特工作并有类似的问题.
成功创建后,如何在点击其UISwitch时选择UITableView的行?
我的模型中有一个布尔值,并希望根据开关的开/关状态切换该布尔值.
我有一些以编程方式创建的包含开关的单元格...
查看控制器:
var settings : [SettingItem] = [
SettingItem(settingName: "Setting 1", switchState: true),
SettingItem(settingName: "Setting 2", switchState: true)
]
override public func tableView(_tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomSettingCell") as! SettingCell
let settingItem = settings[indexPath.row]
cell.settingsLabel.text = settingItem.settingName
cell.settingsSwitch.enabled = settingItem.switchState!
return cell
}
Run Code Online (Sandbox Code Playgroud)
基于SettingItem.swift中的模型:
class SettingItem: NSObject {
var settingName : String?
var switchState : Bool?
init (settingName: String?, switchState : Bool?) {
super.init()
self.settingName = settingName
self.switchState = switchState
}
}
Run Code Online (Sandbox Code Playgroud)
我在SettingCell.swift中有一些出口:
class SettingCell: UITableViewCell {
@IBOutlet weak var settingsLabel: UILabel!
@IBOutlet weak var settingsSwitch: UISwitch!
@IBAction func handledSwitchChange(sender: UISwitch) {
println("switched")
}
Run Code Online (Sandbox Code Playgroud)
产生这个(请忽略格式):

Ant*_*nio 19
当我希望事件从一个单元格传播到包含控制器时,我通常会定义一个自定义委托,如下所示:
protocol SettingCellDelegate : class {
func didChangeSwitchState(# sender: SettingCell, isOn: Bool)
}
Run Code Online (Sandbox Code Playgroud)
在单元格中使用它:
class SettingCell: UITableViewCell {
@IBOutlet weak var settingsLabel: UILabel!
@IBOutlet weak var settingsSwitch: UISwitch!
weak var cellDelegate: SettingCellDelegate?
@IBAction func handledSwitchChange(sender: UISwitch) {
self.cellDelegate?.didChangeSwitchState(sender: self, isOn:settingsSwitch.on)
^^^^
}
}
Run Code Online (Sandbox Code Playgroud)
在视图控制器中实现协议并在单元格中设置委托:
class ViewController : UITableViewController, SettingCellDelegate {
^^^^
override func tableView(_tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomSettingCell") as! SettingCell
let settingItem = settings[indexPath.row]
cell.settingsLabel.text = settingItem.settingName
cell.settingsSwitch.enabled = settingItem.switchState!
cell.cellDelegate = self
^^^^
return cell
}
#pragma mark - SettingCellDelegate
func didChangeSwitchState(#sender: SettingCell, isOn: Bool) {
let indexPath = self.tableView.indexPathForCell(sender)
...
}
}
Run Code Online (Sandbox Code Playgroud)
当点击开关时,事件将传播到视图控制器,新状态和单元格本身作为参数传递.从单元格中,您可以获取索引路径,然后执行您需要的任何操作,例如选择行等.
| 归档时间: |
|
| 查看次数: |
5970 次 |
| 最近记录: |