【问题标题】:Xcode - Swift - UILabel height expanding for textXcode - Swift - UILabel 文本高度扩展
【发布时间】:2015-10-20 12:26:26
【问题描述】:

我想让 UILabel 的高度根据其文本展开。

这是视图控制器的外观,已选择标签:

这是代码(我尝试了很多不同的类似的东西,但这是我现在拥有的):

import UIKit

class ViewControllerTEST: UIViewController {

@IBOutlet weak var label: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()


    label.frame = CGRectMake(0, 0, CGRectGetWidth(label.bounds), 0)
    label.numberOfLines = 0
    label.lineBreakMode = .ByWordWrapping
    label.text = "This is a really\nlong string"
    label.setNeedsLayout()
    label.sizeToFit()
    label.frame = CGRectMake(0, 0, CGRectGetWidth(label.bounds), CGRectGetHeight(label.bounds))



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

而且,正如您在此处看到的,它没有按预期工作:

【问题讨论】:

标签: ios xcode swift uilabel sizetofit


【解决方案1】:

不要使用框架,使用自动布局。为标签添加顶部、前导和尾随约束(我建议在情节提要中这样做)。只要你有lines 等于0(你这样做),高度就会自动调整。如果您想在代码中添加约束,您的 viewDidLoad 将如下所示:

override func viewDidLoad() {
    super.viewDidLoad()
    label.text = "This is a really\nlong string"
    label.setTranslatesAutoresizingMaskIntoConstraints(false)
    view.addSubview(label)
    let views = ["label": label]
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|", options: nil, metrics: nil, views: views))
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]", options: nil, metrics: nil, views: views))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多