How to center text in label with font autoresizing? - ios

I have a label that resizes it's
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
If I set short text, it stays in the center. But if I put long text, it goes down. What do I need to do?
Label constrained to be in X and Y centers of the view.
Short text:
Long text:

Add the following code:
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.label.minimumScaleFactor = 0.4
label.numberOfLines = 1

Set UIlabel Top, hight, >= width and horizontally center constraint see the following image and get the expected output as you want.
Note: Keep the number of line 1 as it is.
Short text output:
Long text output:
Set the following constraint
Top, height, width
Horizontally center constraint
Width is >=

Related

How do I offset UILabel text alignment?

I am trying to offset the center starting point for a UILabel. The problem that I am facing is that I can't make the label text to grow from a point that is offset from center until it reaches one end of the label. Then, I want the text to shift one character to the left with each additional added character until it reaches the the other end. Then it would be acceptable for the text to truncate with an ellipses.
So far, my code looks like this but I don't know where to go from here.
private let amountLabel: UILabel = {
let label = UILabel()
label.textColor = .blue
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
I suggest you put the UILabel into a container view, center horizontally with the offset you want, but set its priority lower than the compression resistance., e.g. 750, compression resistance 999. Then create a trailing constraint >= with priority 1000, and leading constraint >= priority 1000. In that way centering will be the weakest constraint and as the text grows it will shift to the left until it reaches the leading.

UITableViewAutomaticDimension with auto layout

okay I am having trouble creating dynamic cells with tableview. My image collapse and looks like this. It works fine when the description is long but not when it is to short.
Image constraints are: width = 120, height = 160, top = 8, leading = 12.
Title constraints are: top = 8, leading to imageView = 8, trailing = 12.
Description constraints are: top to titleLabel = 5, leading to imageView = 8, trailing = 12, bottom = 12
Now instead of adding the bottom constraint to the description, I added it to the image and then the cell looks something like this.
Now the description is out of place and in the middle, where the it should be right under the title label.
Would really appreciate the help.
You need to do a little change to fix this
Give Bottom of your UIImageView with >= relation with 12 constant
value (750 Priority)
Give Bottom of your Desc label with >= relation with 12 constant value (With That your label text will stick on top ))
So Now the Autolayout Engine has two things to follow
If your Label text is small then UIImageView will be consider as height
If your Label text is larger then it will be used as Cell height
Hope is is helpful

Two labels alignment and its constraints

I have 2 labels: the description label (w/ red background) and the results label (gray text)
How do i set constraints for this example in order to have the results label with the size of its content and the description label until the results leadingAnchor? (like i have in the second row)
Objective C
[self.customTextLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.counterLabel.leadingAnchor].active = YES;
[self.counterLabel.widthAnchor constraintGreaterThanOrEqualToConstant:0].active = YES;
swift
titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: counterLabel.leadingAnchor).isActive = true
counterLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 0).isActive = true
I have a solution that i think it's ugly.
self.counterLabelWidthConstraint = [self.counterLabel.widthAnchor constraintEqualToConstant:0];
self.counterLabelWidthConstraint.active = YES;
And then after i set the text:
self.counterLabelWidthConstraint.constant = [self.counterLabel sizeThatFits:CGSizeMake(CGFLOAT_MAX, self.counterLabel.height)].width;
The way to do this with auto layout is by using the contentCompressionResistancePriority of the 2 labels. Set the pririty to NSLayoutPriorityRequired for the second label and something lower like NSLayoutPriorityDefaultLow for the first label. Then, as long as the 2 labels have proper constraints anchoring them to their superview and each other, the first label should compress while the second label should not.
You just need to increase the horizontal compression resistance of the right/gray label to be higher than that of the left/red label. This tells the visual layout that, in the event that there is not enough space for both labels, the one on the left will be compressed before shrinking the label on the right. 750 is the default for all views, so just increase the right/gray label's horizontal compression resistance to 751 and you should be good to go.
Swift 5 programatically:
<#label#>.setContentCompressionResistancePriority(.required, for: .horizontal)
Labels with this property will not compress horizontally.
You can set constraints for in storyboard itself. Select Label 1 (red back ground) and label's superview set widths are equal constraint. Select Label 1 and double tap on its width constraint, from the resultant window, you could see Lable 1 width equal to superview with value constant as '1'. change '1' to 0.7 or whichever the percentage you want.

NSLabel Autoshrink with top constraints

I try to figure out autoshrink option in UILabel with regarding top constraint.
I have UIView and three labels. One of them has autoshrink option on. It has constraint to be centered, and has Trailing and Top constraint which should shrink label when changing size of UIView. If I make UIVIew thinner, font size is decreased, but if I change height of UIView font is not changed.
Constraints on UILabels :
Align Center X to Superview
Align Center Y to Superview
Trailing Space to Superview >= 50
Top Space to Superview >= 40
Align Center X to label2
Top Space to label1 equals :15
Bottom space to label2 equals :3
Label 1 constraints :
Align Center x to superview
Trailing Space to superview >=10
Leading Space to superview >=10
Bottom Space to Shrink Label equal 15
Label 2 constraint :
Align Center X to Shrink label
Top Space to Shrink label equals 3
How to change this?
What I want is, on last image that label will be nice autoshrink. So if I change width or height of the UIView label should shrink.
plz select your Shrink label set
Number of lines is 0
Line Breaks: Clip
Autoshrink: Minimum Font Scale 0.25
I hope below code will help you in some way,
extension Double {
/// Returns propotional width according to device width
var propotional: CGFloat {
if UIDevice.current.userInterfaceIdiom == .pad {
return CGFloat(414.0) / CGFloat(375.0) * CGFloat(self)
}
return CGFloat(Screen.width) / CGFloat(375.0) * CGFloat(self)
}
}
extension UILabel {
/// This property is change font-size of Label's text propotionaly, if assigned `On` from Interface builder
#IBInspectable
var isPropotional: Bool{
get {
return true
}
set {
if newValue == true {
let fontSize = Double((self.font!.pointSize))
self.font = UIFont(name: self.font!.fontName, size: fontSize.propotional)
}
}
}
}
In extension of Double, propotional value is calculated by considering current device set in storyboard as iPhone 6 size.
After adding this code set on from interface builder for Label where you can see isPropotional attribute in attribute inspector tab. Please refer image.

How to center vertically labels in a view

I have 4 labels like this in a view:
The view hierarchy like this:
But if one of text in each label is empty, all of other labels should center vertically with the image.
For example: the albumDataLabel.text is empty, then userNameLabel, albumNameLabel, albumLocationLabel should center vertically with the image.
Somethings like this:
So how to do this, please point me to some approaches.
Set height constraint for every label and which label have not text
make it's height zero(from outlet of height constraint by setting constant to 0) at runtime.
Your constraint should be in linear hierarchy like first label's top should be pinned with it's supper view's top and last label's bottom should be pinned with superview's bottom and each and every label's bottom should be pinned with top of below label.
then you should set height constraint for view that contains all labels with constant (>=) of minimum height(least height of your view).
and centered vertically that view with your image view.
you can do this kind of setup!!
Since your 4 Labels are already in a view, you can set the labels' constraints to pin the first Label to the top, last Label the bottom and spacing in between to zero
Then select the view(withLabels) and your ImageView to align their vertical centers
Do not set a height value constraint for your labels nor the view
When one of your labels have an empty string, the height is automatically set to zero and hence 'hidden' so the view(withLabels) will shrink in height. All can be done in the interface builder, no coding necessary, it is just a matter of autolayout.
1) for your userNameLabel:
userNameLabel.leftAnchor.constraintEqualToAnchor(imageView.rightAnchor, constant: 10).active = true
userNameLabel.topAnchor.constraintEqualToAnchor(self.topAnchor, constant: 50).active = true
userNameLabel.widthAnchor.constraintEqualToConstant(220).active = true
userNameLabel.heightAnchor.constraintEqualToConstant(30).active = true
2) for your albumNameLabel:
albumNameLabel.widthAnchor.constraintEqualToConstant(220).active = true
albumNameLabel.heightAnchor.constraintEqualToConstant(30).active = true
albumNameLabel.topAnchor.constraintEqualToAnchor(userNameLabel.bottomAnchor, constant: 5).active = true
albumNameLabel.leftAnchor.constraintEqualToAnchor(imageView.leftAnchor, constant: 10).active = true
3) remember this:
self.addSubview(userNameLabel)
self.addSubview(albumNameLabel)
And go on in this way to all elements in your View.

Resources