我已经确认,“addLabel”函数给出的值正在改变,但是当打印出“label.frame.origin.y”时,它总是显示0.目前,代码看起来很糟糕,因为我一直在努力解决这个问题。有什么想法吗?
var newY: Int = 8
var mainViewNewHeight: Int = 251
func setContentFromList(content: [String], target: UIView, targetHeight: NSLayoutConstraint) {
newY = 8
var bullet:UILabel!
let width = Int(UIScreen.main.bounds.width) - 84
let font = UIFont(name: "Helvetica", size: 18)
for item in content {
bullet = UILabel(frame: CGRect(x: 8, y: newY, width: 7, height: 17))
bullet.text = "•"
bullet.textColor = UIColor( red: 183/255, green: 110/255, blue:121/255, alpha: 1.0 )
bullet.font = bullet.font.withSize(18)
let a = CGFloat(newY)
print(a) // Correct
addLabel(y: a, text: item, font: font!, width: CGFloat(width), target: target)
target.addSubview(bullet)
}
mainViewNewHeight += newY
targetHeight.constant = CGFloat(newY)
}
这就是“addLabel”功能:
func addLabel(y: CGFloat, text:String, font:UIFont, width:CGFloat, target: UIView) {
let label:UILabel = UILabel(frame: CGRect(x: 22, y: y, width: width, height: CGFloat.greatestFiniteMagnitude))
print("Label y:", label.frame.origin.y) // Invalid (0.0)
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
newY += Int(label.frame.height)
target.addSubview(label)
}
答案 0 :(得分:1)
您的问题出在CGFloat.greatestFiniteMagnitude
删除integer value
,并将其替换为let label:UILabel = UILabel(frame: CGRect(x: 22, y: y, width: width, height: 20))
,您将看到您的代码可以正常运行。
基本上是这样的:
20.0
Label y: 20.0
41.0
Label y: 41.0
62.0
Label y: 62.0
83.0
Label y: 83.0
打印出来:
@import url('https://fonts.googleapis.com/css?family=El+Messiri');