UILabel centered text – getting the text’s rect
I recently had a section of user interface where I had a UILabel that took up an iPhone’s full width. It contained text which would be dynamic over time, meaning that the text would update at times. I wanted to place an image icon beside the first character of the label, but I needed to know where to place it. I had done it in the past but honestly forgot exactly how to do it.
Kyle Sluder from the Apple Cocoa-Dev list reminded me what I should be looking for.
Doh! I should have decided to RTFM — read the documentation. You can get a rect for the label, but you can’t use all of it for positioning. Here is sample code in how to get the job done.
let label = UILabel(frame: CGRect(x: 0, y: 100, width: self.view.frame.size.width, height: 30)) label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 16) label.numberOfLines = 1 label.text = "This show is crazy." let rect:CGRect = label.textRect(forBounds: label.bounds, limitedToNumberOfLines: 1) let v = UIView(frame: CGRect(x: rect.origin.x, y: label.frame.origin.y, width: rect.width, height: label.frame.height)) v.backgroundColor = UIColor.red.withAlphaComponent(0.3) self.view.addSubview(label) self.view.addSubview(v)
Pretty easy. I just forgot how to do it. This is for the whole text, not substrings within it.