在UITableViewCell上添加一个按钮

时间:2017-04-05 12:00:57

标签: swift uitableview constraints subview uiswitch

我正在为我的设置构建表格视图。由于它们具有默认布局,因此我使用的是UITableViewCellStyles。在几行中我需要一个开关。

在下面的代码中,交换机在我的完整表格视图中“跳转”,尽管添加了切换到单元格!

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

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 .....

}

2 个答案:

答案 0 :(得分:1)

感谢您让我走向正确的方向(cell?.accessoryView)。 let 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

答案 1 :(得分: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

相关问题