在IB中创建的UILabel的自动换行包装?

时间:2015-06-26 10:36:20

标签: ios swift cocoa-touch uilabel

我想在代码中创建一个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)

1 个答案:

答案 0 :(得分:1)

您应该使用CGRectGetMidXCGRectGetMidY常量,而不是计算ScreenWidth和ScreenHeight值。

instructLabel = UILabel(frame: CGRectMake(CGRectGetMidX(self.view.frame),CGRectGetMidY(self.view.frame),self.view.frame,self.view.frame))
相关问题