【问题标题】:Button in center of cell programatically以编程方式位于单元格中心的按钮
【发布时间】:2019-02-05 13:26:14
【问题描述】:

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

如何在不使用 Interface Builder 的任何步骤的情况下以编程方式在单元格的中心添加按钮?

【问题讨论】:

  • 通过将其高度和宽度除以 2 来计算超级视图(容器视图)的中心点,然后补偿按钮框架大小。多田。
  • 或者了解自动布局的工作原理并使用它来定位按钮。

标签: ios swift button cell


【解决方案1】:
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")
}

}

【讨论】:

    【解决方案2】:
    1. 下载一个名为“TinyConstraints”的库,它是 iOS 应用程序开发中的标准。
    2. 将其导入您的 SWIFT 文件。
    3. 将该按钮的子视图添加到您的 tableView 单元格。
    4. 然后尝试类似:Button.centreXAxisInSuperView() 或 YAxis(如果需要),或两者兼而有之...肯定会居中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 2011-03-14
      • 2013-10-09
      相关资源
      最近更新 更多