gpt4 book ai didi

swift - 如何以编程方式向两个 UI 项目(标签和按钮?

转载 作者:行者123 更新时间:2023-11-30 10:28:51 25 4
gpt4 key购买 nike

理想情况下,我希望标签和按钮如下所示:enter image description here

如何以编程方式设置约束?目前我拥有的代码是:

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

let frame: CGRect = tableView.frame

let label: UILabel = {
let lb = UILabel()
lb.translatesAutoresizingMaskIntoConstraints = false
lb.text = "@\(userM) \(postM)"
lb.font = lb.font.withSize(14)
lb.textColor = .black
lb.backgroundColor = .white
lb.numberOfLines = 0
return lb
}()

let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 25))
button.backgroundColor = .blue
button.setTitle("Answer", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)


let header: UIView = {
let hd = UIView()
hd.addSubview(label)
hd.addSubview(button)
label.leadingAnchor.constraint(equalTo: hd.leadingAnchor, constant: 10).isActive = true
label.topAnchor.constraint(equalTo: hd.topAnchor, constant: 10).isActive = true
label.trailingAnchor.constraint(equalTo: hd.trailingAnchor, constant: -10).isActive = true
label.bottomAnchor.constraint(equalTo: hd.bottomAnchor, constant: -10).isActive = true

return hd
}()

return header

}

但是,代码返回的按钮距离屏幕太远,而且格式不正确。我需要在按钮上设置哪些附加约束才能使其位于动态 TextView 的底部并与 UILabel 的左侧对齐? enter image description here

最佳答案

您没有为按钮设置约束。将以下行添加到为 label 设置约束的 block 中:

button.leadingAnchor.constraint(equalTo: hd.leadingAnchor, constant: 10).isActive = true
button.topAnchor.constraint(equalTo: label.bottomAnchor, constant: -10).isActive = true
button.widthAnchor.constraint(equalToConstant: 100).isActive = true
button.bottomAnchor.constraint(equalTo: hd.bottomAnchor, constant: -10).isActive = true

删除label.bottomAnchor.constraint(equalTo: hd.bottomAnchor,constant: -10).isActive = true,你不需要这个约束。

不要忘记实现 func tableView(_ tableView: UITableView,estimatedHeightForHeaderInSection section: Int) -> CGFloatfunc tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat,需要确定表头高度:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return 100
}

关于swift - 如何以编程方式向两个 UI 项目(标签和按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59593632/

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