【问题标题】:Word wrapping for a UILabel not created in IB?未在 IB 中创建的 UILabel 的自动换行?
【发布时间】: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


【解决方案1】:

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

instructLabel = UILabel(frame: CGRectMake(CGRectGetMidX(self.view.frame),CGRectGetMidY(self.view.frame),self.view.frame,self.view.frame))

【讨论】:

  • 即使该类是 UIView 类型,它也没有名为“view”的成员
  • self.bounds 可能对 UIView 有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 2010-11-10
相关资源
最近更新 更多