I have the following code...
UILabel *buttonLabel = [[UILabel alloc] initWithFrame:targetButton.bounds];
buttonLabel.text = #"Long text string";
[targetButton addSubview:buttonLabel];
[targetButton bringSubviewToFront:buttonLabel];
...the idea being that I can have multi-line text for the button, but the text is always obscured by the backgroundImage of the UIButton. A logging call to show the subviews of the button shows that the UILabel has been added, but the text itself cannot be seen. Is this a bug in UIButton or am I doing something wrong?
For iOS 6 and above, use the following to allow multiple lines:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to
[button setTitle: #"Line1\nLine2" forState: UIControlStateNormal];
For iOS 5 and below use the following to allow multiple lines:
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
// you probably want to center it
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setTitle: #"Line1\nLine2" forState: UIControlStateNormal];
2017, for iOS9 forward,
generally, just do these two things:
choose "Attributed Text"
on the "Line Break" popup select "Word Wrap"
The selected answer is correct but if you prefer to do this sort of thing in Interface Builder you can do this:
If you want to add a button with the title centered with multiple lines, set your Interface Builder's settings for the button:
[]
For IOS 6 :
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
As
UILineBreakModeWordWrap and UITextAlignmentCenter
are deprecated in IOS 6 onwards..
To restate Roger Nolan's suggestion, but with explicit code, this is the general solution:
button.titleLabel?.numberOfLines = 0
SWIFT 3
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.setTitle("Button\nTitle",for: .normal)
I had an issue with auto-layout, after enabling multi-line the result was like this:
so the titleLabel size doesn't affect the button size
I've added Constraints based on contentEdgeInsets (in this case contentEdgeInsets was (10, 10, 10, 10)
after calling makeMultiLineSupport():
hope it helps you (swift 5.0):
extension UIButton {
func makeMultiLineSupport() {
guard let titleLabel = titleLabel else {
return
}
titleLabel.numberOfLines = 0
titleLabel.setContentHuggingPriority(.required, for: .vertical)
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
addConstraints([
.init(item: titleLabel,
attribute: .top,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: contentEdgeInsets.top),
.init(item: titleLabel,
attribute: .bottom,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: contentEdgeInsets.bottom),
.init(item: titleLabel,
attribute: .left,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .left,
multiplier: 1.0,
constant: contentEdgeInsets.left),
.init(item: titleLabel,
attribute: .right,
relatedBy: .greaterThanOrEqual,
toItem: self,
attribute: .right,
multiplier: 1.0,
constant: contentEdgeInsets.right)
])
}
}
In Xcode 9.3 you can do it by using storyboard like below,
You need to set button title textAlignment to center
button.titleLabel?.textAlignment = .center
You don't need to set title text with new line (\n) like below,
button.setTitle("Good\nAnswer",for: .normal)
Simply set title,
button.setTitle("Good Answer",for: .normal)
Here is the result,
There is a much easier way:
someButton.lineBreakMode = UILineBreakModeWordWrap;
(Edit for iOS 3 and later:)
someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
Left align on iOS7 with autolayout:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentLeft;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
First of all, you should be aware that UIButton already has a UILabel inside it. You can set it using –setTitle:forState:.
The problem with your example is that you need to set UILabel's numberOfLines property to something other than its default value of 1. You should also review the lineBreakMode property.
Swift 5 , For multi Line text in UIButton
let button = UIButton()
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.titleLabel?.numberOfLines = 0 // for Multi line text
To fix title label's spacing to the button, set titleEdgeInsets and other properties before setTitle:
let button = UIButton()
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.numberOfLines = 0
button.titleEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 20, right: 20)
button.setTitle("Dummy button with long long long long long long long long title", for: .normal)
P.S. I tested setting titleLabel?.textAlignment is not necessary and the title aligns in .natural.
For those who are using Xcode 4's storyboard, you can click on the button, and on the right side Utilities pane under Attributes Inspector, you'll see an option for Line Break. Choose Word Wrap, and you should be good to go.
Answers here tell you how to achieve multiline button title programmatically.
I just wanted to add that if you are using storyboards, you can type [Ctrl+Enter] to force a newline on a button title field.
HTH
Setting lineBreakMode to NSLineBreakByWordWrapping (either in IB or code) makes button label multiline, but doesn't affect button's frame.
If button has dynamic title, there is one trick: put hidden UILabel with same font and tie it's height to button's height with layout; when set text to button and label and autolayout will make all the work.
Note
Intrinsic size height of one-line button is bigger than label's, so to prevent label's height shrink it's vertical Content Hugging Priority must be greater than button's vertical Content Compression Resistance.
You have to add this code:
buttonLabel.titleLabel.numberOfLines = 0;
These days, if you really need this sort of thing to be accessible in interface builder on a case-by-case basis, you can do it with a simple extension like this:
extension UIButton {
#IBInspectable var numberOfLines: Int {
get { return titleLabel?.numberOfLines ?? 1 }
set { titleLabel?.numberOfLines = newValue }
}
}
Then you can simply set numberOfLines as an attribute on any UIButton or UIButton subclass as if it were a label. The same goes for a whole host of other usually-inaccessible values, such as the corner radius of a view's layer, or the attributes of the shadow that it casts.
As to Brent's idea of putting the title UILabel as sibling view, it doesn't seem to me like a very good idea. I keep thinking in interaction problems with the UILabel due to its touch events not getting through the UIButton's view.
On the other hand, with a UILabel as subview of the UIButton, I'm pretty confortable knowing that the touch events will always be propagated to the UILabel's superview.
I did take this approach and didn't notice any of the problems reported with backgroundImage. I added this code in the -titleRectForContentRect: of a UIButton subclass but the code can also be placed in drawing routine of the UIButton superview, which in that case you shall replace all references to self with the UIButton's variable.
#define TITLE_LABEL_TAG 1234
- (CGRect)titleRectForContentRect:(CGRect)rect
{
// define the desired title inset margins based on the whole rect and its padding
UIEdgeInsets padding = [self titleEdgeInsets];
CGRect titleRect = CGRectMake(rect.origin.x + padding.left,
rect.origin.x + padding.top,
rect.size.width - (padding.right + padding.left),
rect.size.height - (padding.bottom + padding].top));
// save the current title view appearance
NSString *title = [self currentTitle];
UIColor *titleColor = [self currentTitleColor];
UIColor *titleShadowColor = [self currentTitleShadowColor];
// we only want to add our custom label once; only 1st pass shall return nil
UILabel *titleLabel = (UILabel*)[self viewWithTag:TITLE_LABEL_TAG];
if (!titleLabel)
{
// no custom label found (1st pass), we will be creating & adding it as subview
titleLabel = [[UILabel alloc] initWithFrame:titleRect];
[titleLabel setTag:TITLE_LABEL_TAG];
// make it multi-line
[titleLabel setNumberOfLines:0];
[titleLabel setLineBreakMode:UILineBreakModeWordWrap];
// title appearance setup; be at will to modify
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setFont:[self font]];
[titleLabel setShadowOffset:CGSizeMake(0, 1)];
[titleLabel setTextAlignment:UITextAlignmentCenter];
[self addSubview:titleLabel];
[titleLabel release];
}
// finally, put our label in original title view's state
[titleLabel setText:title];
[titleLabel setTextColor:titleColor];
[titleLabel setShadowColor:titleShadowColor];
// and return empty rect so that the original title view is hidden
return CGRectZero;
}
I did take the time and wrote a bit more about this here. There, I also point a shorter solution, though it doesn't quite fit all the scenarios and involves some private views hacking. Also there, you can download an UIButton subclass ready to be used.
If you use auto-layout on iOS 6 you might also need to set the preferredMaxLayoutWidth property:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;
In Swift 5.0 and Xcode 10.2
//UIButton extension
extension UIButton {
//UIButton properties
func btnMultipleLines() {
titleLabel?.numberOfLines = 0
titleLabel?.lineBreakMode = .byWordWrapping
titleLabel?.textAlignment = .center
}
}
In your ViewController call like this
button.btnMultipleLines()//This is your button
It works perfectly.
Add to use this with config file like Plist, you need to use CDATA to write the multilined title, like this:
<string><![CDATA[Line1
Line2]]></string>
If you use auto-layout.
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.numberOfLines = 2
swift 4.0
btn.titleLabel?.lineBreakMode = .byWordWrapping
btn.titleLabel?.textAlignment = .center
btn.setTitle( "Line1\nLine2", for: .normal)
Roll your own button class. It's by far the best solution in the long run. UIButton and other UIKit classes are very restrictive in how you can customize them.
In iOS 15 in 2021, Apple for the first time officially supports multi-line UIButtons via the UIButton.Configuration API.
UIButton.Configuration
A configuration that specifies the appearance and behavior of a button and its contents.
This new API is explored in What's new in UIKit as well as the session:
Meet the UIKit button system
Every app uses Buttons. With iOS 15, you can adopt updated styles to create gorgeous buttons that fit effortlessly into your interface. We'll explore features that make it easier to create different types of buttons, learn how to provide richer interactions, and discover how you can get great buttons when using Mac Catalyst.
https://developer.apple.com/videos/play/wwdc2021/10064/
self.btnError.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
self.btnError.titleLabel?.textAlignment = .center
self.btnError.setTitle("Title", for: .normal)
I incorporated jessecurry's answer within STAButton which is part of my STAControls open source library. I currently use it within one of the apps I am developing and it works for my needs. Feel free to open issues on how to improve it or send me pull requests.
Adding Buttons constraints and subviews. This is how i do it in my projects, lets say its much easier like this. I literally 99% of my time making everything programmatically.. Since its much easier for me. Storyboard can be really buggy sometimes
[1]: https://i.stack.imgur.com/5ZSwl.png
My experience:
Go to "Attribut" tab.
Texting in title, press "alt+Enter" while you want to jump to next line.
And check "Word Wrap" under "Attribut --> Control" field.
picture
Related
This post is a separate topic but related to Custom Nav Title offset ios 11
I created a new thread because it is a separate issue.
From project: https://github.com/ekscrypto/Swift-Tutorial-Custom-Title-View
To recreate the problem, simply put a button on the existing Root View Controller that pushes another view controller. The "< Back" button scoots the title over, which makes it terribly uncentered. How can I fix this? Thank you.
Simple change required to support earlier versions of iOS; you should properly resize your custom title view to be the expected width its actually going to be. iOS 11 attempts to resize the width of the title view to fit the available space based on the constraints but iOS 10 and below will try to maintain the size of the view as much as possible.
The solution is therefore to open the MyCustomTitleView.xib file, and to set the width of the MyCustomTitleView to something reasonable like 180pt.
Cheers!
For iOS 10 and below you need to set up CGFrame for your attributed titleLabel.
Here is the code example.
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *titleLabel = [[UILabel alloc]init];
NSDictionary *fontAttribute = #{ NSFontAttributeName:[UIFont fontWithName:#"SFProText-Medium" size:15.f]};
NSAttributedString *str = [[NSAttributedString alloc]initWithString:#"YOUR TITLE"
attributes:fontAttribute];
titleLabel.attributedText = str;
[titleLabel sizeToFit]; // This method create a frame
self.navigationItem.titleView = titleLabel;
}
Swift example:
override func viewDidLoad() {
super.viewDidLoad()
let titleLabel = UILabel()
let title = NSMutableAttributedString(string: "Your title", attributes:[
NSAttributedStringKey.foregroundColor: UIColor.blue,
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17.0, weight: UIFont.Weight.light)])
titleLabel.attributedText = title
titleLabel.sizeToFit()
self.navigationItem.titleView = titleLabel
}
I want to center image to center Y position of first line of text of my UILabel. I use masonry to set Auto Layout constraints like that:
[_haveReadIndicatorImgView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.equalTo(self.contentView).offset(SMALL_OFFSET);
make.height.width.equalTo(#(8));
}];
[_topTxtlbl mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(_haveReadIndicatorImgView.mas_right).offset(TINY_OFFSET);
make.top.equalTo(_haveReadIndicatorImgView.mas_top);
make.right.equalTo(self.arrowImgView.mas_left).offset(-SMALL_OFFSET);
make.bottom.equalTo(_dateTxtLbl.mas_top).offset(-SMALL_OFFSET);
}];
It should be pretty strightforward. I simply attach top of UIImageView to top of my Label.
But take a look at screen.
Top edges of UIImageView (gray dot) and label are equal, but how to make UIImageView to be centered to first line of text like that?
Thanks.
Actually there is a way of doing this! If you use plain old AutoLayout this can be done with the following snippet:
// Aligns the icon to the center of a capital letter in the first line
let offset = label.font.capHeight / 2.0
// Aligns the icon to the center of the whole line, which is different
// than above. Especially with big fonts this makes a visible difference.
let offset = (label.font.ascender + label.font.descender) / 2.0
let constraints: [NSLayoutConstraint] = [
imageView.centerYAnchor.constraint(equalTo: label.firstBaselineAnchor, constant: -offset),
imageView.trailingAnchor.constraint(equalTo: label.leadingAnchor, constant: -10)
]
NSLayoutConstraint.activate(constraints)
The first constraint will display your icon at the Y center of the first line of your label. The second one puts your icon left of the label and creates a 10pt space between them.
Hope this helps!
You derive the middle of the first line by using the lineHeight for the font of your label.
let lineHeight = ceil(multiLineLabel.lineHeight)
let center = lineHeight / 2
Now that you have the center, you can center the haveReadIndicatorImgView's centerYAnchor to the top of your label with a constant: center
I solved this recently by adding a hidden single line label in exactly the same location and font as the multiline one, without a bottom constraint.
Then you can simply align the icon image .centerY to the hidden label's .centerY.
I achieve following by 2 steps:
1) Calculate expected height of label line of text with specific font:
+(CGSize)getSimpleSizeBasedOnFont:(CGFloat)font{
UILabel *lbl = [UILabel new];
lbl.text = #"Simple text";
lbl.font = [UIFont systemFontOfSize:font];
return [lbl.text sizeWithFont:lbl.font
constrainedToSize:lbl.frame.size
lineBreakMode:NSLineBreakByWordWrapping];
}
Then i add constraints to center Y of UIImage View with offset equal to 50% of that height:
CGFloat lblOffs = [Helper getSimpleSizeBasedOnFont:14].height;
[_haveReadIndicatorImgView mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(_topTxtlbl.mas_top).offset(lblOffs/2);
make.left.equalTo(self.contentView).offset(SMALL_OFFSET);
make.height.width.equalTo(#(8));
}];
I have done this differently.
At first i align my imageView with label by FirstBaseLine.
And then i took an outlet of that LayoutConstraint
I have calculated an offset like below:
let offset = (label.font.capHeight + imageView.frame.size.height) / 2 //your bulleted image
I have discarded that offset from FirstBaseLine constant
firstBaseLineConstraintWithLabel.constant -= offset
Here is the output
I have a parent UIView where I place two labels on it. Each of these labels only has one line as can be seen here:
The problem now is that the baseline is wrong. I'm using auto layout and the question is how should my constraints should look like in this case? Especially the verticaly positioning of the labels. These are the constraints I currently have:
H:|-[title]-2-[description]-(>=5)-| //with NSLayoutFormatOptions.AlignAllFirstBaseline
V:|[title]|
V:|[description]|
The above constraints leads to
Unable to simultaneously satisfy constraints.
because the centering and the first baseline constraint are fighting each other. The labels should take the full height of the parent, but with different font size.
I tried to pin the labels to the top/bottom but that doesn't work for all cases.
How should I vertically position my labels?
Instead of using two different label for rich text you can use AttributedString. Here is a example:
- (NSMutableAttributedString*)getRichText {
NSString *str1 = #"I am bold ";
NSString *str2 = #"I am simple";
NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:[str1 stringByAppendingString:str2]];
UIFont *font1=[UIFont fontWithName:#"Helvetica-Bold" size:30.0f];
UIFont *font2=[UIFont fontWithName:#"Helvetica" size:20.0f];
NSInteger l1 = str1.length;
NSInteger l2 = str2.length;
[attString addAttribute:NSFontAttributeName value:font1 range:NSMakeRange(0,l1)];
[attString addAttribute:NSFontAttributeName value:font2 range:NSMakeRange(l1,l2)];
return attString;
}
In View did load you can set the string to label as below:
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 50)];
[self.view addSubview:textLabel];
textLabel.attributedText = [self getRichText];
Output:
To see what happens, make the background of the label yellow. You have ambiguous constraints.
To fix it, remove the last vertical constraint. You don't need it.
This here works in my testing playground:
let titleLabel = UILabel()
titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
titleLabel.font = UIFont.boldSystemFontOfSize(30)
titleLabel.text = "title"
hostView.addSubview(titleLabel)
let descriptionLabel = UILabel()
descriptionLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
descriptionLabel.font = UIFont.boldSystemFontOfSize(20)
descriptionLabel.text = "description"
hostView.addSubview(descriptionLabel)
let views = ["title": titleLabel, "description": descriptionLabel]
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[title]-2-[description]-(>=5)-|", options: NSLayoutFormatOptions.AlignAllFirstBaseline, metrics: nil, views: views))
NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: hostView, attribute: .CenterY, multiplier: 1.0, constant: 0.0).active = true
Result:
what you need to do is fairly simple.
You two labels (the objects) just need to have the same size in height.
To do so add constraints to your first label (for exemple 40 px).
When it's done elect the first AND the second label then in your contraints menu on the bottom of the screen (the one one the left, add new alignement constraint) select top edges and bottom edges.
Then you can set your width top bottom etc however you want.
Enjoy
I have a UIButton and the text of the button is filled by a randomiser.
However my problem is that sometimes the number of characters in a text is too many, leading to the button now showing the whole text.
Would it be possible to check if the characters are too many and then have it drop the rest of the text to another text line? So basically having to text lines instead of one for the UIButton?
Objectivc-C
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.numberOfLines = 2;
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if u need
else use this
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
[button setTitle: #"Line1\nLine2" forState: UIControlStateNormal];
Swift
button.titleLabel!.lineBreakMode = .ByWordWrapping
button.titleLabel!.numberOfLines = 2
button.titleLabel!.textAlignment = .Center
else use this
button.titleLabel!.lineBreakMode = .ByWordWrapping
button.titleLabel!.textAlignment = .Center
button.setTitle("Line1\nLine2", forState: .Normal)
Swift3
buttonName.titleLabel!.lineBreakMode = .byWordWrapping
buttonName.titleLabel!.textAlignment = .center
buttonName.setTitle("Line1\nLine2", for: .normal)
In the Interface Builder, change the Line Break mode to Word Wrap for the UIButton control:
And to center the text, make the title Attributed instead of Plain.
Assuming you are using a storyboard or .xib file, click on your button and open the Attributes inspector on the right, then in the Button section, look for the 'Line Break' field. Drop this down and you will see 2 options (among others) - 'Character wrap' and 'Word wrap', these provide the functionality you are after.
alternatively In code you can use one of the following
[BUTTON setLineBreakMode:NSLineBreakByWordWrapping]
[BUTTON setLineBreakMode:NSLineBreakByCharWrapping]
I had a problem with UILabels growing when auto layout was used rather than word wrapping. The solution was to set the preferredMaxLayoutWidth to force it to wrap the text.
For a button you can do the same thing using:
button.titleLabel.preferredMaxLayoutWidth = <max width required>.
I need to display an email address on the left side of a UIButton, but it is being positioned to the centre.
Is there any way to set the alignment to the left side of a UIButton?
This is my current code:
UIButton* emailBtn = [[UIButton alloc] initWithFrame:CGRectMake(5,30,250,height+15)];
emailBtn.backgroundColor = [UIColor clearColor];
[emailBtn setTitle:obj2.customerEmail forState:UIControlStateNormal];
emailBtn.titleLabel.font = [UIFont systemFontOfSize:12.5];
[emailBtn setTitleColor:[[[UIColor alloc]initWithRed:0.121 green:0.472 blue:0.823 alpha:1]autorelease] forState:UIControlStateNormal];
[emailBtn addTarget:self action:#selector(emailAction:) forControlEvents:UIControlEventTouchUpInside];
[elementView addSubview:emailBtn];
[emailBtn release];
Set the contentHorizontalAlignment:
// Swift
emailBtn.contentHorizontalAlignment = .left;
// Objective-C
emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
You might also want to adjust the content left inset otherwise the text will touch the left border:
// Swift 3 and up:
emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);
// Objective-C
emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
You can also use interface builder if you don't want to make the adjustments in code.
Here I left align the text and also indent it some:
Don't forget you can also align an image in the button too.:
In Swift 3+:
button.contentHorizontalAlignment = .left
Swift 4+
button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
UIButton *btn;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
Using emailBtn.titleEdgeInsets is better than contentEdgeInsets, in case you don't want to change the whole content position inside the button.
Here is explained how to do it and why it works so:
http://cocoathings.blogspot.com/2013/03/how-to-make-uibutton-text-left-or-right.html
in xcode 8.2.1 in the interface builder it moves to:
There is a small error in the code of #DyingCactus.
Here is the correct solution to add an UILabel to an UIButton to align the button text to better control the button 'title':
NSString *myLabelText = #"Hello World";
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
// position in the parent view and set the size of the button
myButton.frame = CGRectMake(myX, myY, myWidth, myHeight);
CGRect myButtonRect = myButton.bounds;
UILabel *myLabel = [[UILabel alloc] initWithFrame: myButtonRect];
myLabel.text = myLabelText;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.textColor = [UIColor redColor];
myLabel.font = [UIFont fontWithName:#"Helvetica Neue" size:14.0];
myLabel.textAlignment = UITextAlignmentLeft;
[myButton addSubview:myLabel];
[myLabel release];
Hope this helps....
Al
For Swift 2.0:
emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
This can help if any one needed.
In Swift 5.0 and Xcode 10.2
You have two ways to approaches
1) Direct approach
btn.contentHorizontalAlignment = .left
2) SharedClass example (write once and use every ware)
This is your shared class(like this you access all components properties)
import UIKit
class SharedClass: NSObject {
static let sharedInstance = SharedClass()
private override init() {
}
}
//UIButton extension
extension UIButton {
func btnProperties() {
contentHorizontalAlignment = .left
}
}
In your ViewController call like this
button.btnProperties()//This is your button
Try
button.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;
tl;dr: Using UIButton.Configuration - do titleAlignment = .center but also add a subtitle and make its font microscopic.
So, we're on iOS 15+, we're using the new UIButton.Configuration APIs, buttons now go multi-line by default and you're trying to figure out - how do I make the button's title be centered or trailing aligned, as opposed to the default (leading). For example you have an image and a button title underneath and and you want it centered.
Seems reasonable to try this:
configuration.titleAlignment = .center
But it doesn't change anything.
By trying thing out in Interface Builder, I noticed the following: titleAlignment only has an effect if there is a subtitle along with the title.
I am not sure if this is an omission on Apple's side (which might be fixed later) or if there is a good reason for it. In any case, we need a way to make it work without a subtitle. Perhaps some clever contentInset or UIControl.contentHorizontalAlignment can do the trick, but I'd be worried to use these in cases where we have to think about other languages, dynamic type etc.
Here's a solution which is still hacky, but would do the job:
Add a subtitle which contains just a space, then make the font microscopic, e.g. 0.01.
This is how to do it in code, assuming you are already working with a UIButton.Configuration:
configuration.titleAlignment = .center
configuration.title = "Hello hi"
configuration.subtitle = " "
configuration.subtitleTextAttributesTransformer = UIConfigurationTextAttributesTransformer({ input in
var output = input
output.font = .systemFont(ofSize: 0.01)
return output
})
Not an ideal solution and it might break in the future, but for some use cases the best available solution at the moment.
if you use button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), you will get an warning that states 'contentEdgeInsets' was deprecated in iOS 15.0: This property is ignored when using UIButtonConfiguration. An alternative solution is:
iOS 15.0+
var button: UIButton = {
let button = UIButton(configuration: .filled())
button.configuration?.contentInsets = NSDirectionalEdgeInsets(top: 16, leading: 20, bottom: 16, trailing: 20)
button.contentHorizontalAlignment = .leading
return button
}()
SwiftUI
You should change the alignment property of the .frame modifier applied to the Text. Additionally, set the multiline text alignment to .leading.
Button {
// handler for tapping on the button
} label: {
Text("Label")
.frame(width: 200, alignment: .leading)
.multilineTextAlignment(.leading)
}