问题
I want to show Button title like this

but my output is comming like this even after centralising the title

frmbtn.setTitle("From Station\nSTN\nSTATION NAME", forState: UIControlState.Normal)
frmbtn.titleLabel!.numberOfLines = 3
frmbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center
And Can we put different text sizes in the button title ?
回答1:
Here is whole as you want.

import UIKit
class ViewController: UIViewController {
@IBOutlet var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
var str : NSMutableAttributedString = NSMutableAttributedString(string: "From station\nSTN\nStation Name")
str.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(20), range: NSRange(location: 13,length: 3))
button.setAttributedTitle(str, forState: UIControlState.Normal)
button.titleLabel!.lineBreakMode = .ByWordWrapping
button.titleLabel?.textAlignment = .Center
button.titleLabel?.adjustsFontSizeToFitWidth = true
}
}
回答2:
in Easy way you can also give space like this:
frmbtn.setTitle("From Station\n STN\nSTATION NAME", forState: UIControlState.Normal) \\give here space after \n and see the result
frmbtn.titleLabel!.numberOfLines = 3
frmbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center
回答3:
You have to set the text alignment on the titleLabel
itself. Also you can change the font size as part of the font
property.
scanButton.titleLabel!.numberOfLines = 3
scanButton.titleLabel!.textAlignment = NSTextAlignment.Center;
scanButton.titleLabel!.font = UIFont.systemFontOfSize(40);
回答4:
To set a multiline title on a UIButton, check this forum post which describes changing the button label.
myButton.titleLabel.textAlignment = UITextAlignmentCenter;
myButton.titleLabel.lineBreakMode = UILineBreakModeCharacterWrap;
[myButton setTitle:@"From Station STN station name" forState:UIControlStateNormal];
来源:https://stackoverflow.com/questions/30543245/centralise-the-title-of-uibutton-as-show-in-the-image-below-swift