Irshad Qureshi
Irshad Qureshi

Reputation: 819

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

I want to show Button title like this

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

frmbtn is the outlet of button And the Code I am Using for this is

 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 ?

Upvotes: 1

Views: 1387

Answers (4)

Badal Shah
Badal Shah

Reputation: 7602

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

Upvotes: 3

iAnurag
iAnurag

Reputation: 9356

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

Upvotes: 1

Ashish Kakkad
Ashish Kakkad

Reputation: 23872

Here is whole as you want.

enter image description here

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

    }
}

Upvotes: 4

Dash
Dash

Reputation: 17408

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

Upvotes: 1

Related Questions