我有一个带有一个标签和开关的自定义单元格,我想存储当用户访问该 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/