UILabel Align Text to center

后端 未结 10 1726
心在旅途
心在旅途 2020-12-12 11:19

How do I align text in UILabel?

相关标签:
10条回答
  • 2020-12-12 11:42

    To center text in a UILabel in Swift (which is targeted for iOS 7+) you can do:

    myUILabel.textAlignment = .Center
    

    Or

    myUILabel.textAlignment = NSTextAlignment.Center
    
    0 讨论(0)
  • 2020-12-12 11:43

    In Swift 4.2 and Xcode 10

    let lbl = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
    lbl.textAlignment = .center //For center alignment
    lbl.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
    lbl.textColor = .white
    lbl.backgroundColor = .lightGray//If required
    lbl.font = UIFont.systemFont(ofSize: 17)
    
     //To display multiple lines in label
    lbl.numberOfLines = 0
    lbl.lineBreakMode = .byWordWrapping
    
    lbl.sizeToFit()//If required
    yourView.addSubview(lbl)
    
    0 讨论(0)
  • 2020-12-12 11:48

    From iOS 6 and later UITextAlignment is deprecated. use NSTextAlignment

    myLabel.textAlignment = NSTextAlignmentCenter;
    

    Swift Version from iOS 6 and later

    myLabel.textAlignment = .center
    
    0 讨论(0)
  • 2020-12-12 11:49

    Use yourLabel.textAlignment = NSTextAlignmentCenter; for iOS >= 6.0 and yourLabel.textAlignment = UITextAlignmentCenter; for iOS < 6.0.

    0 讨论(0)
  • 2020-12-12 11:50

    Here is a sample code showing how to align text using UILabel:

    label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
    label.textAlignment = NSTextAlignmentCenter;
    

    You can read more about it here UILabel

    0 讨论(0)
  • 2020-12-12 11:50

    N.B.: As per the UILabel class reference, as of iOS 6 this approach is now deprecated.

    Simply use the textAlignment property to see the required alignment using one of the UITextAlignment values. (UITextAlignmentLeft, UITextAlignmentCenter or UITextAlignmentRight.)

    e.g.: [myUILabel setTextAlignment:UITextAlignmentCenter];

    See the UILabel Class Reference for more information.

    0 讨论(0)
提交回复
热议问题