import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Main View"
//Set label height based on Text length, font and size...
addLabel()
}
func addLabel(){
let myLabel = UILabel()
myLabel.textColor = UIColor.black
myLabel.backgroundColor = UIColor.cyan
myLabel.numberOfLines = 0;
myLabel.font = UIFont(name: "Marker Felt", size: 24)
myLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(myLabel)
myLabel.text =
"""
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
let maxWidth = view.bounds.size.width - 40
let maximumLabelSize: CGSize = CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude)
let expectedLabelSize: CGSize = myLabel.sizeThatFits(maximumLabelSize)
// create a frame that is filled with the UILabel frame data
var newFrame: CGRect = myLabel.frame
// resizing the frame to calculated size
newFrame.size.height = expectedLabelSize.height
// put calculated frame into UILabel frame
myLabel.frame = newFrame
var allConstraints: [NSLayoutConstraint] = []
let views = ["view": view!, "myLabel": myLabel]
let horizontalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "H:|-[myLabel]-(>=10)-|", metrics: nil, views: views)
allConstraints += horizontalConstraints
let verticalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "V:|-(>=40)-[myLabel]", metrics: nil, views: views)
allConstraints += verticalConstraints
NSLayoutConstraint.activate(allConstraints)
}
}
All one can think and do in a short time is to think what one already knows and to do as one has always done!
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.