gpt4 book ai didi

swift - footerView 中的中心按钮

转载 作者:行者123 更新时间:2023-11-28 15:14:50 25 4
gpt4 key购买 nike

我希望我的按钮位于 footerView 的中心。我尝试了几种方法,但每次都失败了:

1.

    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRect.zero)
footerView.backgroundColor = UIColor(rgba: "#F9FAFB")
let button = UIButton(frame: CGRect(x:(footerView.frame.size.width - 30) / 2, y:(footerView.frame.size.height - 30) / 2, width: 30, height: 30)) button.setImage(UIImage(named: "gen-cog"), for: .normal)
button.addTarget(self, action: #selector(footerButtonAction), for: .touchUpInside)
footerView.addSubview(button)
}
  1. 使用自动布局,这使我的按钮居中但打破了它的宽度和高度,我在上面设置为 30。

    let centerYCon = NSLayoutConstraint(item: button,
    attribute: .centerY,
    relatedBy: .equal,
    toItem: footerView,
    attribute: .centerY,
    multiplier: 1.0,
    constant: 0.0);
    footerView.addConstraint(centerYCon)

    let centerXCon = NSLayoutConstraint(item: button,
    attribute: .centerX,
    relatedBy: .equal,
    toItem: footerView,
    attribute: .centerX,
    multiplier: 1.0,
    constant: 0.0);
    footerView.addConstraint(centerXCon)
    footerView.addSubview(button)

3.

button.center = footerView.center

最佳答案

  button.translatesAutoresizingMaskIntoConstraints = false
footerView.addSubview(button)

现在再添加两个额外的约束。

  let widthConstraint = NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30)
let heightConstraint = NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30)
button.addConstraints([widthConstraint, heightConstraint])

关于swift - footerView 中的中心按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com