Centralise the title of UIButton as show in the Image Below Swift

青春壹個敷衍的年華 提交于 2019-12-06 16:19:45

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

    }
}

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

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);

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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!