Auto-sizing a UILabel without setting an explicit height - ios

How do I get a multi-line label to size itself? I don't want to set an explicit height for it but I do need to place it in view.
The way my app is built, we explicitly set frames and origins rather than using NSLayoutConstraints. It's a mature app so this isn't up for discussion.
I'd like to be able to give my UILabel an origin and a width and let it figure its own height out.
How can I do this? This is my playground code:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 180))
view.backgroundColor = .white
let l = UILabel()
l.text = "this is a really long label that should wrap around and stuff. it should maybe wrap 2 or three times i dunno"
l.textColor = .black
l.lineBreakMode = .byWordWrapping
l.numberOfLines = 0
l.textAlignment = .center
l.sizeToFit()
let margin: CGFloat = 60
view
view.addSubview(l)
l.frame = CGRect(x: margin, y: 0, width: view.bounds.width - (margin * 2), height: 100)
// I don't want to do this ^^

This may do what you want...
As requested, you want to set the .origin and .width of a UILabel and have it set its own .height based on the text.
class ZackLabel: UILabel {
override public func layoutSubviews() {
super.layoutSubviews()
let h = sizeThatFits(CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude))
self.frame.size.height = h.height
}
}
class ViewController: UIViewController {
var testLabel: ZackLabel!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
// instantiate a 300 x 180 UIView at 20, 80
let myView = UIView(frame: CGRect(x: 20, y: 80, width: 300, height: 180))
myView.backgroundColor = .white
// instantiate a ZackLabel
testLabel = ZackLabel()
testLabel.text = "this is a really long label that should wrap around and stuff. it should maybe wrap 2 or three times i dunno"
testLabel.textColor = .black
testLabel.lineBreakMode = .byWordWrapping
testLabel.numberOfLines = 0
testLabel.textAlignment = .center
// set background color so we can see its frame
testLabel.backgroundColor = .cyan
let margin: CGFloat = 60
// set label's origin
testLabel.frame.origin = CGPoint(x: margin, y: 0)
// set label's width (label will set its own height)
testLabel.frame.size.width = myView.bounds.width - margin * 2
// add the view
view.addSubview(myView)
// add the label to the view
myView.addSubview(testLabel)
// add a tap recognizer so we can change the label's text at run-time
let rec = UITapGestureRecognizer(target: self, action: #selector(tapFunc(_:)))
view.addGestureRecognizer(rec)
}
#objc func tapFunc(_ sender: UITapGestureRecognizer) -> Void {
testLabel.text = "This is dynamic text being set."
}
}
Result (on an iPhone 8):
and, after tapping on the (yellow) view, dynamically changing the text:

label.sizeThatFits(CGSize(width: <your required width>, height: CGFloat.greatestFiniteMagnitude))
This returns the labels needed size, growing infinitely in height, but fitted to your required width. I've occasionally noticed minor inaccuracies with this function (rounding error?), so I tend to bump the width and height by 1 just to be safe.

UILabel comes with an intrinsic size that should be calculated based on the text and the label's .font property. You may need to add a margin to it...
var height = l.intrinsicContentSize.height
height += margin
l.frame = CGRect(x: margin, y: 0, width: view.bounds.width - (margin * 2), height: height)
Failing that, maybe you can try something like:
let size = CGSize(width: view.bounds.width - (margin * 2), height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
var estimatedFrame = CGRect()
if let font = l.font {
estimatedFrame = NSString(string: l.text).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: font], context: nil)
}
//if you need a margin:
estimatedFrame.height += margin
l.frame = estimatedFrame

Give your UILabel as a UIScrollview or UITableView cell subview.
Then you setup UILabel leading, tralling, top, bottom constrain.
If you give UITableview then set table view hight auto dynamic. If you give UIScrollview
just set UILabel bottom constrain priority low

Related

How to set custom title view to center of navigation bar

I am trying to add custom view (Label) as title view of navigation item.
but it is not appearing in centre
func setupNavigationMultilineTitle(title:String) {
let autoscrollLabel = EFAutoScrollLabel()
autoscrollLabel.text = title
autoscrollLabel.textAlignment = .center
autoscrollLabel.backgroundColor = .red
autoscrollLabel.font = AppTheme.Fonts.font(type: .Medium, size: 15)
autoscrollLabel.textColor = AppTheme.Colors.ColorsOfApp.header_color.color
autoscrollLabel.frame = CGRect(x: 0, y: 0, width:((self.navigationController?.navigationBar.frame.size.width ?? 0) - (self.navigationItem.leftBarButtonItem?.customView?.frame.width ?? 0) * 2) , height: 40)
self.navigationItem.titleView = autoscrollLabel
}
I have tried to use deduct width of custom view to show it in center but unfortunately it is not working.
I have also tried to get self.navigationItem.leftBarButtonItem.width but it returns 0. I confirmed that there is leftBarbutton item with po self.navigationItem.leftBarButtonItem
EDIT
This solves issue
autoscrollLabel.frame = CGRect(x: self.view.center.x - 125, y: 0, width: 250 , height: 40)
But I need dynamic solution
Any help would be appreciated
I debugged your scenario, hope it helps you and other developers,
When we assign tittleView width by calculating the space left after subtracting space of items, margins, padding etc then iOS calculate titleView X from the right side i.e. titleview.x = rightItem.x - width and we are expecting it like titleview.x = navbar.width/2 - width/2.
Please look below sample test cases.
Calculate width
let maxItemOnEitherSide = max(arrLeftItems.count, arrRightItems.count)
let widthOfItem : CGFloat = 30.0
let pading : CGFloat = 40
let aWidth : CGFloat = (self.navigationController?.navigationBar.frame.width)! - CGFloat(maxItemOnEitherSide) * widthOfItem * 2.0 - pading
let lblNavTitle = UILabel(frame: CGRect(x: 0, y: 0,
width: aWidth,
height: 40))
Case 1 : arrLeftItems.count = 1 and arrRightItems.count = 0.
Output :
Case 2 : arrLeftItems.count = 0 and arrRightItems.count = 1.
Hope above cases clear you out what we are expecting and what we are getting and the calculation that I wrote in first para i.e. titleview.x = rightItem.x - width.
Conclusion :
If rightBarItems have more items than leftBarItems then titleview will be in center, so you wont need to do anything but if leftBarItems have more items than rightBarItems then add blank items in right side to make it balance. It is weird for developers but seems like its the only solution.
Check the final output.
View Heirarchy
Output
If your navigation Item is part of a UINavigationController you could try
self.navigationController?.navigationBar.topItem?.leftBarButtonItem?.width ?? 0.0
Add my version code based on #dahiya_boy answers.
In my case, I have a custom button that has a more 30-width size. So, rather than multiply it by 30, I find a max from left and right items to find the max.
Below is the code:
func setCenterTitle(_ title: String) {
let navWidth = (navigationController?.navigationBar.frame.width).orZero
let leftItemsWidth = leftBarButtonItems.orEmptyArray.reduce(0) {
$0 + ($1.customView?.frame.width).orZero
}
let rightItemsWidth = rightBarButtonItems.orEmptyArray.reduce(0) {
$0 + ($1.customView?.frame.width).orZero
}
let maxItemsWidth = max(leftItemsWidth, rightItemsWidth)
let padding: CGFloat = 40
let labelWidth = navWidth - (maxItemsWidth * 2) - padding
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: labelWidth, height: 40))
titleLabel.text = title
titleLabel.textAlignment = .center
titleLabel.font = UIFont.boldSystemFont(ofSize: 16)
self.titleView = titleLabel
}

Programmatically display UIScrollView in Swift

I have view controller with views: top level View Contains Container View which contains two views: bottomView, topView, as shown.
Scene
I want to display from: to: date range in the topView. In the bottomView I want to display a UIScrollView that contains two columns which I can scroll. I did that but the topView and BottomView overlap when I introduce scrollView. When I scroll I can see the views getting separated and as soon as i Let go the scrollbar they overlap again.
can someone tell me how to fix it? I just don't seem to understand how the scrollView and bottomView are to be associated.
Code below:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
//scrollView.frame = innerView.bounds
innerView.frame = CGRect(x:0, y:0, width:scrollView.contentSize.width, height:scrollView.contentSize.height)
}
func buildBottomView () {
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let ht:Int = 21
let incrX:Int = 5
let incrY:Int = 5
let gapCol1:Int = 5
let col1Width:Int = 65
let col2Width:Int = 65
let startY:Int = 5
let col1StartX:Int = 10
let col2StartX:Int = col1StartX + col1Width + gapCol1
var loadRowStartY: Int = 0
// column headers
categoryColumnLabel.text = "Interval"
categoryColumnLabel.font = UIFont.preferredFont(forTextStyle:UIFontTextStyle.subheadline)
//categoryColumnLabel.font = UIFont.systemFont(ofSize: 14)
categoryColumnLabel.frame = CGRect(x: col1StartX, y:startY, width: col1Width, height: ht)
categoryColumnLabel.textAlignment = NSTextAlignment.left
categoryColumnLabel.tag = 1
innerView.addSubview(categoryColumnLabel)
valueColumnLabel.text = "Values"
valueColumnLabel.font = UIFont.preferredFont(forTextStyle:UIFontTextStyle.subheadline)
//valueColumnLabel.font = UIFont.systemFont(ofSize: 14)
valueColumnLabel.frame = CGRect(x: col2StartX, y:startY, width: col2Width, height: ht)
valueColumnLabel.textAlignment = NSTextAlignment.center
valueColumnLabel.tag = 3
innerView.addSubview(valueColumnLabel)
let sepLine:UIView = UIView()
sepLine.frame = CGRect(x: col1StartX, y:startY+ht+incrY, width: Int(screenWidth-20), height: 2)
sepLine.backgroundColor = UIColor.darkGray
sepLine.tag = 60
loadRowStartY = startY+ht+incrX+ht
innerView.addSubview(sepLine)
for i in 0 ..< 24 {
let timeIntervalLabel = UILabel()
let value2Label = UILabel()
print("display load profile")
let loadStruct = loadDict[String(i)] as! CommercialProfile
print (loadStruct.timeInterval)
timeIntervalLabel.text = loadStruct.timeInterval
timeIntervalLabel.font = UIFont.preferredFont(forTextStyle:UIFontTextStyle.caption1)
//valueColumnLabel.font = UIFont.systemFont(ofSize: 14)
timeIntervalLabel.frame = CGRect(x: col1StartX, y:loadRowStartY, width: col1Width, height: Int(timeIntervalLabel.font.lineHeight))
timeIntervalLabel.textAlignment = NSTextAlignment.center
innerView.addSubview(timeIntervalLabel)
print(loadStruct.value)
value2Label.text = loadStruct.value
value2Label.font = UIFont.preferredFont(forTextStyle:UIFontTextStyle.caption1)
//value2Label = UIFont.systemFont(ofSize: 14)
value2Label.frame = CGRect(x: col2StartX, y:loadRowStartY, width: col2Width, height: Int(value2Label.font.lineHeight))
value2Label.textAlignment = NSTextAlignment.center
innerView.addSubview(value2Label)
loadRowStartY = loadRowStartY + incrY + Int(value2Label.font.lineHeight)
}
you are setting the bounds of the scrollView to the size of the whole view with this code: scrollView.frame = view.bounds.
The scrollView only needs to scroll the content in the bottom view. Scroll Views have their own content, that is normally larger than the viewable area of the screen/view. The scroll view just allows you to pan the viewport of that view.
So add the bottom view and setup your constraints on that. add the scrollView to the bottom view and then add your content into the scrollView.
Make sure that your bottom view has clipToBounds set to true and then you should be able to keep the headers in place and just scroll the content.
I'll try and put an example together for you shortly.
EDIT:
I've just created this simple example which shows the scroll behaviour you need. This works in a playground or just as a simple view controller. I've intentionally not used auto layout or setup constraints due to time, but you will see what you need to solve your issue
class ViewController: UIViewController {
var topView: UIView!
var bottomView: UIView!
var scrollView: UIScrollView!
var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let screenSize = UIScreen.main.bounds
self.topView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: 100))
self.bottomView = UIView(frame: CGRect(x: 0, y: 100, width: screenSize.width, height: screenSize.height - 100))
self.scrollView = UIScrollView(frame: CGRect(x: 0, y: 100, width: screenSize.width, height: screenSize.height - 100))
self.contentView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height * 3))
self.view.backgroundColor = .white
self.view.addSubview(self.topView)
self.view.addSubview(self.bottomView)
self.bottomView.addSubview(self.scrollView)
self.scrollView.addSubview(self.contentView)
self.bottomView.clipsToBounds = true
self.scrollView.contentSize = CGSize(width: screenSize.width, height: screenSize.height * 3)
self.contentView.backgroundColor = .gray
}
}

How to fill a label with text until it reaches it's width

I want to know if there is a way to determine if a UILabel is full of text.
For example, if a have a label with size of:
| |
I want to know when the label is full of text, such as:
|.........|
I need to fill its with dots until it reaches the textFields width.
Well, If I got it right, probably what are you looking for is Label intrinsicContentSize:
The natural size for the receiving view, considering only properties
of the view itself.
the width of the label intrinsicContentSize should be the actual width of the label, doesn't matter what's the frame.size.width value.
Based on that, you simply implement:
let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 21))
print(lbl.frame.size.width)
// 150.0
lbl.text = ""
let intrinsicSizeWidth = lbl.intrinsicContentSize.width
// since the label text is still empty, its value should be 0.0
print(intrinsicSizeWidth)
while lbl.intrinsicContentSize.width < lbl.frame.size.width {
lbl.text?.append(".")
}
print(lbl.text!)
// ................................
Note that increasing your label width would leads to contains more dots:
let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
.
.
.
print(lbl.text!)
// ...........................................
Obviously, if you would like to compare it with a UITextField -for instance- (as you mentioned in the question), it should be:
// "textField" the name of your text field...
while lbl.intrinsicContentSize.width < textField.frame.size.width {
lbl.text?.append(".")
}
Create label with frame and default text
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 100))
label.text = ""
Populate text with dots until text's width reaches label's width
while label.sizeThatFits(label.frame.size).width <= label.frame.width {
label.text = label.text! + "."
}

Get height of UIView based on specific width before showing view

I have a UIView which I have designed in Interface Builder. It basically consists out of a header image and some text (UILabel) below. The view is being shown modally with a custom Transition and doesn't fill the whole screen.
There is like a 20 pixels margin on the left and right and 40 px on the top. The UILabel gets filled with some text that's coming from the web. What I want do do, is to find (or should I say predict) the height of the whole view for a specific width. How can I do that?
I had similar problem, but instead of calculating font size and image height you can use this UIView extension that will autosize your view with max width:
extension UIView {
func autosize(maxWidth: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
let dummyContainerView = UIView(frame: CGRect(x: 0, y: 0, width: maxWidth, height: 10000000))
dummyContainerView.addSubview(self)
dummyContainerView.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true
dummyContainerView.leftAnchor.constraint(equalTo: leftAnchor, constant: 0).isActive = true
dummyContainerView.rightAnchor.constraint(equalTo: rightAnchor, constant: 0).isActive = true
setNeedsLayout()
layoutIfNeeded()
removeFromSuperview()
frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
translatesAutoresizingMaskIntoConstraints = true
}
}
Using this approuch you don't have to worry about your content inside the view.
To use it:
let customView: CustomView = ... //create your view
... // configure all data on your view, e.g. labels with correct text
customView.autosize(maxWidth: 150) // resize your view
view.addSubview(customView) // add your view to any view
You need to have both the picture and the label before calculating the aspected size.
I guess you should use something like this (maybe adding the vertical inter-distance between the imageView and the Label to the sum, and maybe removing the lateral margins from the width):
objective C :
- (CGFloat)preferredHeightFromWidth:(CGFloat)width text:(NSString *)text font:(UIFont *)font image:(UIImage *)image
{
// Calculate label height
CGFloat labelHeight = [text
boundingRectWithSize:CGSizeMake(width, 10000)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:font}
context:[[NSStringDrawingContext alloc] init]
].size.height;
// Calculate image height
CGFloat ratio = image.size.height/ image.size.width;
CGFloat imageHeight = (ratio * width);
// Do the sum
return labelHeight + imageHeight;
}
Swift:
func preferredHeight(width: CGFloat, text: NSString, font: UIFont, image: UIImage) -> CGFloat {
// Calculate Label Height
let labelRect = text.boundingRect(
with: CGSize.init(width: width, height: 10000),
options: .usesLineFragmentOrigin,
attributes: [NSFontAttributeName : font],
context: NSStringDrawingContext())
let labelHeight = labelRect.height
// Calculate Image Height
let ratio = image.size.height / image.size.width
let imageHeight = ratio / width
// Calculate Total Height
let height = labelHeight + imageHeight
// Return Height Value
return height
}
(Thanks to Christopher Hannah for swift version)
Here is the same answer as Alberto, but I have changed it into Swift 3.
func preferredHeight(width: CGFloat, text: NSString, font: UIFont, image: UIImage) -> CGFloat {
// Calculate Label Height
let labelRect = text.boundingRect(
with: CGSize.init(width: width, height: 10000),
options: .usesLineFragmentOrigin,
attributes: [NSFontAttributeName : font],
context: NSStringDrawingContext())
let labelHeight = labelRect.height
// Calculate Image Height
let ratio = image.size.height / image.size.width
let imageHeight = ratio / width
// Calculate Total Height
let height = labelHeight + imageHeight
// Return Height Value
return height
}

Position of rightView UITextField

Is there a way to adjust the position of a rightView on UITextField? I tried setting the frame on the view (set as rightView) but it didn't change anything.
I'd like to avoid making two views, one as the rightView and one as the rightView's subview where I change the subview's position, if possible.
The right overlay view is placed in the rectangle returned by the rightViewRectForBounds: method of the receiver.
So I suggest you subclass UITextField and override this method, something like this:
#interface CustomTextField: UITextField
#end
#implementation CustomTextField
// override rightViewRectForBounds method:
- (CGRect)rightViewRectForBounds:(CGRect)bounds{
CGRect rightBounds = CGRectMake(bounds.origin.x + 10, 0, 30, 44);
return rightBounds ;
}
#Puneet Sharma's answer was great but that would give the need to create a class that would subclass UITextField, what I did instead was create a UIView that would act as a padding.
This code works without the need to subclass
Here's my code, although it's written in Swift 3
// this is the view I want to see on the rightView
let checkImageView = UIImageView(image: UIImage(named: "check24.png"))
checkImageView.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
checkImageView.curveEdges(12)
checkImageView.contentMode = .scaleAspectFit
// declare how much padding I want to have
let padding: CGFloat = 6
// create the view that would act as the padding
let rightView = UIView(frame: CGRect(
x: 0, y: 0, // keep this as 0, 0
width: checkImageView.frame.width + padding, // add the padding
height: checkImageView.frame.height))
rightView.addSubview(checkImageView)
// set the rightView UIView as the textField's rightView
self.textField.rightViewMode = .whileEditing
self.textField.rightView = rightView
What happened here is, that the rightView which is a UIView that has a transparent colored background which then gave the illusion that there is a padding whereas there is not.
Right Padding you can use as
let imageview = UIImageView(image: UIImage(named: "image name"))
imageview.contentMode = .center
let rightPadding: CGFloat = 14 //--- change right padding
imageview.frame = CGRect(x: 0, y: 0, width: imageview.frame.size.width + rightPadding , height:imageview.frame.size.height)
textField.rightViewMode = .always
textFieldd.rightView = imageview

Resources