How to change Button Title Alignment in Swift? - ios

I am trying to set the title on a Button to left. But everything i tried is not working.
With:
UILabelButton.titleLabel.textAlignment = .Left
Or:
UILabelButton.contentVerticalAlignment = UIControlContentVerticalAlignment // There is no left
The button title is still centered.
Is there another Property?

Use contentHorizontalAlignment.You have to use UIControlContentHorizontalAlignment.Left.You need to usehorizontal not vertical.
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
Swift 3.x
btn.contentHorizontalAlignment = .left

Swift 4
Sample code
For my requirement I want alignment left top
btnAddress.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
btnAddress.contentVerticalAlignment = UIControlContentVerticalAlignment.top
Swift 5 update:
btnAddress.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
btnAddress.contentVerticalAlignment = UIControl.ContentVerticalAlignment.top

btnAddress.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
btnAddress.contentVerticalAlignment = UIControl.ContentVerticalAlignment.top
And now if you want the text to have some space from left add this
btnAddress.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)

You can also use the below solution (using Storyboard)
step1 :
set the horizontal alignment to left
By default button property have left content inset set to 10 i.e padding for the button from left side
you can see in the below image the left content inset is set to 10 for Left
so change that to 0, if you don't need any padding from left or set the number you want
This way you can set the button title to Left aligned

like this with swift 4:
btnAddress.contentHorizontalAlignment = .center

The Most Easiest and smallest Solution:
Button("0"){}.frame(width:160.0,height:70.0,alignment:Alignment.leading)
Check this by using this code for a button you will see that button text is now aligned to "LEFT"

Related

What causes horizontal padding around title of UIButton?

I programmatically created two UIButtons and constrained them to 2 points apart (horizontally). I see extra space, so I clicked the "Debug View Hierachy" button in Xcode, and here is what I see:
What is causing the extra space around the "abc" title? I looked at a few suspect properties of the button and they are all zero. (contentEdgeInsets, titleEdgeInsets)
I haven't done anything to the buttons other than:
let b = UIButton(type: .system)
b.translatesAutoresizingMaskIntoConstraints = false
b.setTitle("...", for: .normal)
The constraints look like:
b1.centerXAnchor.constraint(equalTo: outer.centerXAnchor)
b2.leftAnchor.constraint(equalTo: b1.rightAnchor, constant: 2)
b2.firstBaselineAnchor.constraint(equalTo: b1.firstBaselineAnchor, constant: 0)
UIButton has an intrinsic minimum width of 30-pts.
So, if the title text is shorter than 30-pts, the button's title label will be centered horizontally in the button's 30-pt frame.
You can explicitly set the width to less than 30, but then you'll have to take some other steps to get your button to auto-size with a longer title.

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

Intrinsic content size of button with text only

I have a uibutton, i want to set text dynamically at run time with padding top: 10, bottom 10 and left: 10 and right: 10, once i set text button title cliped. Any one can provide solution.
You must be attentive to fontSize of the button. Setting text programmatically doesn't automatically fits the text. Following code will help you.
//Swift
let btnLabel = yourButton.titleLabel
btnLabel.adjustsFontSizeToFitWidth = true
//Objective C
UILabel *btnLabel = yourButton.titleLabel;
btnLabel.adjustsFontSizeToFitWidth = true
Happy Coding <3

Swift UILabel with horizontal lines on both sides

I am trying to create a UILabel that has 2 horizontal lines on the left and right side like this:
Does anyone know the best approach for doing this in Swift? The content text in the center will change so I want to make sure it can adapt. I'd really like to create some kind of reusable UIView class but I'm not sure where to start?
Thank you!
You can take two UIview of height 1 or 2 pixels of both side of the label. so it's look likes line!!
And you should set background color to black of that view!
Hope this will help :)
Take one UIView with height of 2. Set leading & Trailing according to Super View.
Now take one UILabel with background color white and put Vertically Center to line view.
Make both Center same.
Your work done.
For more help please refer below image.
You can use an extension on UILabel
public extension UILabel {
func drawLineOnBothSides(labelWidth: CGFloat, color: UIColor) {
let fontAttributes = [NSFontAttributeName: self.font]
let size = self.text?.size(attributes: fontAttributes)
let widthOfString = size!.width
let width = CGFloat(1)
let leftLine = UIView(frame: CGRect(x: 0, y: self.frame.height/2 - width/2, width: labelWidth/2 - widthOfString/2 - 10, height: width))
leftLine.backgroundColor = color
self.addSubview(leftLine)
let rightLine = UIView(frame: CGRect(x: labelWidth/2 + widthOfString/2 + 10, y: self.frame.height/2 - width/2, width: labelWidth/2 - widthOfString/2 - 10, height: width))
rightLine.backgroundColor = color
self.addSubview(rightLine)
}
}
This will add a horizontal line of width of 1.0 on the both side of your label. If you don't add text for your label, it will show two horizontal lines through center with some spaces in between them.
As others have mentioned, you can achieve this using three views:
Add a View to your scene to use as a container. I called this view "Lined Label Holder."
To that container, add two Views, one to produce the line on either side of the label.
Add the label in between the two views, and give it some text. Due to the "height = Test.height" constraint on the Lined Label Holder, The intrinsic height of this label is used to calculate the container's height.
The label is allowed to grow with added text and the lines will always start 5px away from the edges of the text and extended to the edges of the container, whose width can be set independently.
This image shows the required constraints:
Use one UIView with black background and height of 1px, set label background to white, align its text to center and align UILabel to center of UIView (there is no need for 2 views since label white background will cover UIView).
Not necessary 2 UIView's.
Take 1 UIView and give background black color.Add the constraints necessary with: height=2.
place 1 label on the center and give required constraints

Adjust font size of text to fit in UIButton

I want to make sure the button text fits into a UIButton, while the UIButton has a fixed size.
Of course I can access the titleLabel of the UIButton.
In a label I would set autoshrink to minimum font scale which seems to correspond to
self.myButton.titleLabel.adjustsFontSizeToFitWidth = YES;
, but doesn't really behave the same, since it only makes the text fits horizontally into the bounds, not vertically, thereby not changing the font size.
How can i actually adjust the font size of a label programmatically to make the text fit into the label bounds (as shown in Goal in the picture below) ?
I already tried
self.myButton.titleLabel.numberOfLines = 0;
self.myButton.titleLabel.minimumScaleFactor = 0.5f;
without success, always ended up as in adjustsFontSizeToFitWidth on the left side of the pic above.
Edit: The solution also has to be ios7 compliant
self.mybutton.titleLabel.minimumScaleFactor = 0.5f;
self.mybutton.titleLabel.numberOfLines = 0; <-- Or to desired number of lines
self.mybutton.titleLabel.adjustsFontSizeToFitWidth = YES;
... did the trick, after layoutIfNeeded in viewDidLoad
As it turns out, all those must be set to actually adjust the font-size, not just making it fit into the frame.
Update for Swift 3:
mybutton.titleLabel?.minimumScaleFactor = 0.5
mybutton.titleLabel?.numberOfLines = 0 <-- Or to desired number of lines
mybutton.titleLabel?.adjustsFontSizeToFitWidth = true
Updated code for Swift 3.0:
yourButton.titleLabel?.minimumScaleFactor = 0.5
yourButton.titleLabel?.numberOfLines = 0
yourButton.titleLabel?.adjustsFontSizeToFitWidth = true
You can also set a User Defined Runtime Attribute in Interface Builder for the button where
titleLabel.adjustsFontSizeToFitWidth = true
to make text horizontally and vertically fit with button bounds :
1 - set button alignment like image (* VERY IMPORTANT *)
2 - add this lines of code in your ViewController
btnTest.setTitle("Test for multi line in button show line in button show Test for multi line in button show line in button show", for: .normal)
btnTest.titleLabel!.textAlignment = .center
btnTest.titleLabel!.numberOfLines = 0
btnTest.titleLabel!.adjustsFontSizeToFitWidth = true
btnTest.titleLabel!.minimumScaleFactor = 0.5
// below line to add some inset for text to look better
// you can delete or change that
btnTest.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
note that DON'T using btnTest.titleLabel!.lineBreakMode = NSLineBreakMode.byWordWrapping or other BreakMode in your code . for enable multiline in button . just using from above code
final result :
Try to call the following method.
button.titleLabel?.baselineAdjustment = UIBaselineAdjustment.AlignCenters
try this:
[myButton setFont:[[myButton font] fontWithSize:--originalButtonFontSize]];
textWidth = [text sizeWithFont:[myButton font]].width;
}
In Storyboard, Go to Link Break in Attributes Inspector, see word wrap..or set according to your choice.
In Xcode->Open storyboard->Go to attributes inspector->Control->Alignment->Choose second in both horizontal and vertical.
or
YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
If you prefer do in storyboard, just click the button, then show attributes inspector, and set the line break to "Word Wrap".

Resources