gpt4 book ai didi

ios - 使用 Swift 将 UILabel 动态定位到内容 View 的底部?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:17 25 4
gpt4 key购买 nike

我试图将我动态创建的 UILabel 定位到我的 contentView 的底部。我正在使用名为 Fuzi 的 HTML 解析器来捕获 HTML 标签并基于它们创建 UILabel;

func stringFromHTML( _ string: String?)
{
do{
let doc = try HTMLDocument(string: string!, encoding: String.Encoding.utf8)
if let root = doc.body {
for element in root.children {
if element.tag == "h2" {
// Create new label
let label = UILabel()
label.text = element.stringValue
label.numberOfLines = 0
label.font = UIFont(name: "Avenir Next", size: 17)
label.textColor = UIColor.black
self.contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false

// Label constraints
let labelLeading = NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 20)
let labelTrailing = NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -20)
let labelTop = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: self.contentView.frame.origin.y)

self.contentView.addConstraints([labelLeading, labelTrailing, labelTop])

}
updateContentViewHeight()
}
}

}
catch{
print("html error\n",error)
}

}

func updateContentViewHeight(){
var totalContentHeight:CGFloat = 0.0
for i in self.contentView.subviews {
totalContentHeight += i.frame.height
}
let contentViewHeight:NSLayoutConstraint = NSLayoutConstraint(item: self.contentView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: totalContentHeight-29)
self.contentView.addConstraint(contentViewHeight)

}

我尝试在 viewDidAppear 中调用我的 stringFromHTML 函数。但它会将我的 UILabel 定位到很远的地方(它们似乎没有)。

我想把我的标签放在最后一个标签的底部,见下图;

My screen...

有人可以帮忙吗?提前致谢!

最佳答案

改变

let labelTop = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: self.contentView.frame.origin.y)

if label != nil {
let labelTop = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: label[index], attribute: .top, multiplier: 1, constant: 2)
} else {
let labelTop = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: self.contentView.frame.origin.y)
}

因为您基本上是在强制每个标签位于相同的 y 位置。

关于ios - 使用 Swift 将 UILabel 动态定位到内容 View 的底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40446971/

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