Inf*_*911 4 xcode uilabel ios sizetofit swift
我想根据文字的大小扩大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.
}
*/
}
Run Code Online (Sandbox Code Playgroud)
而且,正如您在此处所看到的,它无法按预期工作:
不要使用框架,使用autolayout.向标签添加顶部,前导和尾随约束(我建议在故事板中执行此操作).只要你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))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4744 次 |
| 最近记录: |