You use UIView.sizeThatFits to get the best size to fit a given size.
(Xcode 8, Swift 3.0)
- To get width, fix the height and maximize the width of your given size.
- To get height, fix the width and maximize the height of your given size.
Code Example of Getting Width of Text
@IBOutlet weak var sampleTextLabel: UILabel!
@IBOutlet weak var widthTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Fix the height to get the width.
let suggestedSize = CGSize(width: CGFloat.greatestFiniteMagnitude,
height: sampleTextLabel.frame.height)
widthTextField.text = sampleTextLabel.sizeThatFits(suggestedSize).width.description
}
Note: CGFloat.greatestFiniteMagnitude gives you the maximum number for a float.(Xcode 8, Swift 3.0)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.