ios - Xcode - Swift - 文本的 UILabel 高度扩展

标签 ios xcode swift uilabel sizetofit

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

这是 View Controller 的样子,选中了标签:

enter image description here

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

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.
}
*/

}

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

enter image description here

最佳答案

不要使用框架,使用自动布局。向标签添加顶部、前导和尾随约束(我建议在 Storyboard 中这样做)。只要您的 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))
}

关于ios - Xcode - Swift - 文本的 UILabel 高度扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31701878/

相关文章:

ios - 不能在属性初始值设定项中使用实例成员 'movies1',属性初始值设定项在 'self' 可用之前运行

ios - 编程等效于 UIViewController 的 "Resize View From NIB"属性

iphone - 将 self 分配给 CLLocationManager.delegate 会生成不兼容类型警告

swift - Xcode 11.4 中 Assets 目录编译 (atool) 失败

ios - 使用 UIImagePickerController 预选图像

objective-c - 从 Swift 访问 Objective-C 变量/函数

ios - PFQuery 仅返回 100 个有限制的对象 (iOS)

iphone - 通过浏览下一页的 iOS 蓝牙连接

ios - 使用 Microsoft Azure SDK 在 iOS 中固定 SSL 证书

ios - 比较 ios Swift 中的时间