Center text in a UILabel

后端 未结 8 629
醉话见心
醉话见心 2021-02-03 16:39

How do you center the text inside a UILabel?

8条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-03 17:08

    The Code is

    [yourLabel setTextAlignment:UITextAlignmentCenter];
    

    or (of course) the Obj-C 2.0 Dot-Syntax

    yourLabel.textAlignment = UITextAlignmentCenter;
    

    For iOS 6 (and higher) you should use NSTextAlignmentCenter instead of UITextAlignmentCenter:

    yourLabel.textAlignment = NSTextAlignmentCenter;
    

    Source

    And if you want backward compatibiliy to iOS 5 also you can do this,

    #ifdef __IPHONE_6_0
    # define ALIGN_CENTER NSTextAlignmentCenter
    #else
    # define ALIGN_CENTER UITextAlignmentCenter
    #endif
    

    Swift 3

    yourLabel.textAlignment = .center
    

提交回复
热议问题