【发布时间】:2015-06-26 10:36:19
【问题描述】:
我正在尝试完全用代码创建UILabel,而不是 IB。
我希望 x,y 角的位置和宽度是固定的,但高度会根据显示的文本数量以及要换行和居中的文本而有所不同。文本是从其他地方填充的。 (不过通常不会超过 2 行)
我已经做到了这一点,但不知道如何使高度可变并让文本换行:
instructLabel = UILabel(frame: CGRectMake(ScreenWidth/2-350, ScreenHeight-ScreenHeight*0.2, 700, 50)) // Guess I don't want the 50 height here though?
instructLabel.backgroundColor = UIColor.blackColor()
instructLabel.preferredMaxLayoutWidth = 700 // does this conflict with above or override?
instructLabel.lineBreakMode = .ByWordWrapping
instructLabel.textAlignment = NSTextAlignment.Center
instructLabel.text = ""
instructLabel.font = FontSmall
instructLabel.textColor = UIColor.whiteColor()
self.addSubview(instructLabel)
【问题讨论】:
-
你想使用自动布局吗?
-
你需要设置
instructionLabel.numberOfLines=0让它增长。默认值为 1,这将导致截断而不是换行。或者将其设置为您想要的最大行数。我会为所有这些和自动布局使用约束。 -
嗨 Bannings - 如果可能的话,我想尝试在代码中实现它!
-
非常感谢罗里。现在工作正常!
标签: ios swift cocoa-touch uilabel