Programmatically Creating Uilabel

How to create UILabel programmatically using Swift?

Creating a UILabel programmatically in Swift 3+:

override func viewDidLoad() {
super.viewDidLoad()

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 285)
label.textAlignment = .center
label.text = "I'm a test label"

self.view.addSubview(label)
}

Creating UILabel programmatically with constraints?

Like you said, we already have x, y and height available for the label, i.e.

let x: CGFloat = 0
let y: CGFloat = 0
let height: CGFloat = 50

Let's create a label using the above details. Also set the width of the label as UIScreen.main.bounds.width as per your requirement.

let label = UILabel(frame: CGRect(x: x, y: y, width: UIScreen.main.bounds.width, height: height))
label.text = "This is a sample text"

Don't forget to set label's translatesAutoresizingMaskIntoConstraints as false and add it to whatever subview you want.

label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)

Add the relevant constraints of label with its superview - top, bottom, leading, height. You can definitely add bottom constraint if required. That totally depends upon your UI.

I'm adding the label to the top of the viewController's view.

NSLayoutConstraint.activate([
label.heightAnchor.constraint(equalToConstant: height),
view.topAnchor.constraint(equalTo: label.topAnchor),
view.leadingAnchor.constraint(equalTo: label.leadingAnchor),
view.trailingAnchor.constraint(equalTo: label.trailingAnchor)
])

Programmatically Creating UILabel

Does the following work ?

UIFont * customFont = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
NSString * text = [self fromSender];

CGSize labelSize = [text sizeWithFont:customFont constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];

UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, labelSize.width, labelSize.height)];
fromLabel.text = text;
fromLabel.font = customFont;
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.minimumScaleFactor = 10.0f/12.0f;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];

edit : I believe you may encounter a problem using both adjustsFontSizeToFitWidth and minimumScaleFactor. The former states that you also needs to set a minimumFontWidth (otherwhise it may shrink to something quite unreadable according to my test), but this is deprecated and replaced by the later.

edit 2 : Nevermind, outdated documentation. adjustsFontSizeToFitWidth needs minimumScaleFactor, just be sure no to pass it 0 as a minimumScaleFactor (integer division, 10/12 return 0).
Small change on the baselineAdjustment value too.

Swift 3 Create UILabel programmatically and add NSLayoutConstraints

See below code as an example

let lblNew = UILabel()
lblNew.backgroundColor = UIColor.blue
lblNew.text = "Test"
lblNew.textColor = UIColor.white
lblNew.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(lblNew)

let widthConstraint = NSLayoutConstraint(item: lblNew, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 300)
let heightConstraint = NSLayoutConstraint(item: lblNew, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)
var constraints = NSLayoutConstraint.constraints(
withVisualFormat: "V:[superview]-(<=1)-[label]",
options: NSLayoutFormatOptions.alignAllCenterX,
metrics: nil,
views: ["superview":view, "label":lblNew])

view.addConstraints(constraints)

// Center vertically
constraints = NSLayoutConstraint.constraints(
withVisualFormat: "H:[superview]-(<=1)-[label]",
options: NSLayoutFormatOptions.alignAllCenterY,
metrics: nil,
views: ["superview":view, "label":lblNew])

view.addConstraints(constraints)

view.addConstraints([ widthConstraint, heightConstraint])

Creating a function to programmatically create UILabels from a String Array in Swift4

Using a collection view is the best option. It makes your job easier. Try this

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
var wordsArr = [String]()

override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(WordCell.self, forCellWithReuseIdentifier: "WordCell")
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(5)-[collectionView]-(5)-|", options: [], metrics: nil, views: ["collectionView":collectionView]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(5)-[collectionView]-(5)-|", options: [], metrics: nil, views: ["collectionView":collectionView]))

createALabel(inputtedString: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam")
}
func createALabel(inputtedString: String) -> Void {
wordsArr = inputtedString.components(separatedBy: " ")
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return wordsArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WordCell", for: indexPath) as? WordCell ?? WordCell()
cell.label.text = wordsArr[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (wordsArr[indexPath.row] as NSString).boundingRect(with: CGSize.zero, options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: 16.0)], context: nil).size.width
let size = CGSize(width: width + 10
, height: 35)
return size
}

}
class WordCell: UICollectionViewCell {

let label = UILabel()

override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {

backgroundColor = .white

label.font = UIFont.systemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = UIColor.blue
label.layer.borderColor = UIColor.blue.cgColor
label.layer.borderWidth = 3.0
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)

addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[label(35)]|", options: [], metrics: nil, views: ["label":label]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[label]|", options: [], metrics: nil, views: ["label":label]))
}
}

Sample Image

Add UILabel to CollectionViewCells programmatically

You are doing wrong in this line nameLabel = UILabel(frame: self.frame), actually you are giving same position as collection view cell's position (x and y coordinates), which is wrong. You need to give nameLabel's positions x=0 and y=0, then it will work fine. Define the nameLabel's frame as below:

var nameLabel:  UILabel = UILabel(frame: CGRect.zero)

override init(frame : CGRect) {
super.init(frame : frame)
nameLabel.frame.size = CGSize(width: self.frame.width, height: self.frame.height)
}

Output as below:

Sample Image

Programmatically adding UILabel is not visible

You need to understand the difference between Frame and Bounds.
The Frame of the view is the position of the view in it's super view, so his origin can have any value of a CGPoint.
The Bounds are just the view itself, so it always have an origin of (0,0)

I think the problem is

label_1.frame = CGRect(x: self.popularView.frame.minX + 3, y: self.popularView.frame.minY, width: self.popularView.frame.width, height: 20)

try to change in

label_1.frame = CGRect(x: self.popularView.bounds.minX + 3, y: self.popularView.bounds.minY, width: self.popularView.frame.width, height: 20)

or

label_1.frame = CGRect(x: 3, y: 0, width: self.popularView.frame.width, height: 20)


Related Topics



Leave a reply



Submit