Ios 以编程方式将按钮置于单元格中心
我试图使其在单元格的中心内有一个“重置进度”按钮。我发现的其他帖子只展示了如何在左侧或右侧添加按钮,或者需要在Interface Builder中执行之前的步骤 如何在界面生成器中无需任何步骤的情况下,以编程方式在单元格中心添加按钮Ios 以编程方式将按钮置于单元格中心,ios,swift,button,cell,Ios,Swift,Button,Cell,我试图使其在单元格的中心内有一个“重置进度”按钮。我发现的其他帖子只展示了如何在左侧或右侧添加按钮,或者需要在Interface Builder中执行之前的步骤 如何在界面生成器中无需任何步骤的情况下,以编程方式在单元格中心添加按钮 class YourCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style
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")
}
}
按钮。centreXAxisInSuperView()
或YAxis(如果需要),或者两者都可以。。。那肯定会使它居中的通过将superview(容器视图)的高度和宽度除以2来计算其中心点,然后补偿按钮框架尺寸。或者了解自动布局的工作原理,并用它来定位按钮。