以编程方式位于单元格中心的按钮

时间:2018-08-30 14:41:04

标签: ios swift button cell

我正在尝试做到这一点,以便在单元格的中心内有一个“重置进度”按钮。我发现的其他帖子仅显示了如何在左侧或右侧添加按钮,或者如何在Interface Builder中执行先前的步骤。

如何在Interface Builder中以编程方式在单元格中心添加按钮而无需任何步骤?

2 个答案:

答案 0 :(得分:0)

class YourCell: UITableViewCell {

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    addSubview(button)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

lazy var button: UIButton = {
    let button = UIButton()
    button.backgroundColor = .blue
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    return button
}()

override func layoutSubviews() {
    super.layoutSubviews()

    button.frame = CGRect(x: 0, y: 0, width: 150, height: 50)
    button.center = self.center
}

@objc func buttonAction() {
    print("Button has been pressed")
}

}

答案 1 :(得分:-2)

  1. 下载名为“ TinyConstraints”的库,这是iOS App开发中的标准。
  2. 将其导入您的SWIFT文件。
  3. 将该按钮的子视图添加到tableView单元格中。
  4. 然后尝试类似的操作:Button.centreXAxisInSuperView()或YAxis(如果需要),或同时使用这两种方法……可以确保其居中。
相关问题