向UITableViewCell添加一个按钮

问题描述:

我正在为我的设置构建表视图。由于他们有默认的布局我正在使用UITableViewCellStyles。在几行我需要一个开关。向UITableViewCell添加一个按钮

在下面的代码中,开关在我的完整表格视图中“跳跃”,尽管将切换添加到单元格中!

如何将交换机添加到具有默认样式的单元格?

PS:我知道如何使用自定义单元来做到这一点,但如果不需要,我不想构建它们。

let mySwitch: UISwitch = { 
    let assign = UISwitch() 
    assign.setOn(true, animated: true) 
    assign.addTarget(self, action: #selector(ContactDetailsVC.assignSwitch), for: .valueChanged) 
    return assign 
}() 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    // case ..... 

    var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cellId") 

    cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cellId") 
    cell?.textLabel?.text = "Test" 
    cell?.contentView.addSubview(mySwitch) 
    cell?.translatesAutoresizingMaskIntoConstraints = false 
    cell?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": mySwitch])) 
    cell?.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": mySwitch])) 

    return cell! 

    // case ..... 

} 
+0

如果你想定制你的小区(例如一个开关按钮),你不应该使用默认的风格细胞即可。 –

你可以用accessoryView试试它。

let mySwitch: UISwitch = { 
let assign = UISwitch() 
assign.setOn(true, animated: true) 
assign.addTarget(self, action: #selector(ContactDetailsVC.assignSwitch), for: .valueChanged) 
return assign 
}() 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

// case ..... 

var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cellId") 

cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cellId") 
cell?.textLabel?.text = "Test" 
cell?.accessoryView = mySwitch 
return cell! 


} 

https://developer.apple.com/reference/uikit/uitableviewcell/1623219-accessoryview

+0

在UIView中添加开关,并将该视图分配给accessoryView –

谢谢你把我在正确的方向(细胞?.accessoryView)。 [让mySwith也没有工作,所以我改变了代码:

var mySwitch = UISwitch() 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    // case ..... 

    var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cellId") 
    cell?.accessoryView = mySwitch 
    mySwitch.setOn(true, animated: true) 
    mySwitch.addTarget(self, action: #selector(SettingsVC.mySwitched), for: .valueChanged) 

    // case