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

我是研究僧i 提交于 2019-12-08 03:32:39

问题


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 ?


回答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

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