如何使用Swift以编程方式创建UILabel?


115

如何UILabel在Xcode 6中使用Swift以编程方式创建?

我已经开始使用Xcode 6中的新“单视图应用程序”,并为该项目选择了Swift。我有我的文件AppDelegate.swiftViewController.swift并且不确定从这里做什么。


1
我建议您从这里开始学习:Swift文档并开始阅读Raywenderlich Tutorials
Prashant

Answers:


251
override func viewDidLoad()
{
  super.viewDidLoad()
  var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
  label.center = CGPointMake(160, 284)
  label.textAlignment = NSTextAlignment.Center
  label.text = "I'm a test label"
  self.view.addSubview(label)
}  

Swift 3.0+更新:

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 285)
label.textAlignment = .center
label.text = "I'm a test label"
self.view.addSubview(label)

2
你不必暗示这个声明为的UILabel,它是从的UILabel()推断
CW0007007

5
您不应该对标签框架进行硬编码-当文本更改或文本本地化并更改字符数时会发生什么?
佐拉尔

您还可以查看此博客,该博客以编程方式描述了如何添加UITextField,UITextView和UILabel:webindream.com/how-to-change-ui-elements-programmatic
farhad rubel 2015年

@iSuresh您如何知道CGPoint(x:160,y:285)将成为他们正在使用的模型的中心?
戴夫G

2
@rommex为此,请调用label.sizeToFit()
乔什·沃尔夫

26

这是Swift 3的正确代码,并附有注释以供指导:

override func viewDidLoad()
{
    super.viewDidLoad()

    // CGRectMake has been deprecated - and should be let, not var
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))

    // you will probably want to set the font (remember to use Dynamic Type!)
    label.font = UIFont.preferredFont(forTextStyle: .footnote)

    // and set the text color too - remember good contrast
    label.textColor = .black

    // may not be necessary (e.g., if the width & height match the superview)
    // if you do need to center, CGPointMake has been deprecated, so use this
    label.center = CGPoint(x: 160, y: 284)

    // this changed in Swift 3 (much better, no?)
    label.textAlignment = .center

    label.text = "I am a test label"

    self.view.addSubview(label)
}

感谢
Gourav-

14

只是要添加到已经很不错的答案上,您可能想要在项目中添加多个标签,因此进行所有这些操作(设置大小,样式等)将很麻烦。为了解决这个问题,您可以创建一个单独的UILabel类。

  import UIKit

  class MyLabel: UILabel {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeLabel()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeLabel()
    }

    func initializeLabel() {

        self.textAlignment = .left
        self.font = UIFont(name: "Halvetica", size: 17)
        self.textColor = UIColor.white

    }

}

要使用它,请执行以下操作

import UIKit

class ViewController: UIViewController {

     var myLabel: MyLabel()

     override func viewDidLoad() {
          super.viewDidLoad()

          myLabel = MyLabel(frame: CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2, width: 100, height: 20))
          self.view.addSubView(myLabel)
     }


}

正是我想要的!
madprogramer

谢谢男人,我有一个问题,如果我想将字符串传递self.text给班级内部来像这样发起:myLabel = MyLabel(string: "text")
Daniel Beltrami

我只是想知道如何使用您的班级,并像这样打电话:myLabel.text = "text"
Daniel Beltrami

11

Swift 4.X和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 //If you want to display only 2 lines replace 0(Zero) with 2.
lbl.lineBreakMode = .byWordWrapping //Word Wrap
// OR
lbl.lineBreakMode = .byCharWrapping //Charactor Wrap

lbl.sizeToFit()//If required
yourView.addSubview(lbl)

如果您的班级中有多个标签,请使用扩展名添加属性。

//Label 1
let lbl1 = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl1.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl1.myLabel()//Call this function from extension to all your labels
view.addSubview(lbl1)

//Label 2
let lbl2 = UILabel(frame: CGRect(x: 10, y: 150, width: 230, height: 21))
lbl2.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl2.myLabel()//Call this function from extension to all your labels
view.addSubview(lbl2)

extension UILabel {
    func myLabel() {
        textAlignment = .center
        textColor = .white
        backgroundColor = .lightGray
        font = UIFont.systemFont(ofSize: 17)
        numberOfLines = 0
        lineBreakMode = .byCharWrapping
        sizeToFit()
    }
}

8

您可以使用以下代码创建标签。更新。

let yourLabel: UILabel = UILabel()
yourLabel.frame = CGRect(x: 50, y: 150, width: 200, height: 21)
yourLabel.backgroundColor = UIColor.orange
yourLabel.textColor = UIColor.black
yourLabel.textAlignment = NSTextAlignment.center
yourLabel.text = "test label"
self.view.addSubview(yourLabel)

5

UILabelviewDidLoad类外创建视图,然后将该视图添加到viewDidLoadmethod中的主视图中。

lazy var myLabel: UILabel = {


    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "This is label view."
    label.font = UIFont.systemFont(ofSize: 12)
    return label
}()

然后添加viewviewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(myLabel)

    // Set its constraint to display it on screen
    myLabel.widthAnchor.constraint(equalToConstant:  200).isActive = true
    myLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    myLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}

@I Love Coding,能否请您解释一下您的代码。[惰性var myLabel:UILabel = {}()]。这会很有帮助。谢谢....
iOS

1
@iOS创建变量时,因为lazy var variable_name = ""它不会消耗您的内存,除非您的应用调用了该变量。如果不使用该属性,则它将永远不会执行。
我喜欢编码

然后,我们将在项目中惰性地创建所有变量,以提高性能。我对吗?
iOS

@iOS是的!最好在您的应用中使用该变量类型以获得更好的性能。另外,您还应该能够了解Thread,以获得更好的性能。
我喜欢编码

4

另一个代码swift3

let myLabel = UILabel()
    myLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    myLabel.center = CGPoint(x: 0, y: 0)
    myLabel.textAlignment = .center
    myLabel.text = "myLabel!!!!!"
    self.view.addSubview(myLabel)

4

另一种使用闭包的方法是使用Swift 4将代码分离为更整洁的东西:

class theViewController: UIViewController {

    /** Create the UILabel */
    var theLabel: UILabel = {
        let label = UILabel()
        label.lineBreakMode = .byWordWrapping
        label.textColor = UIColor.white
        label.textAlignment = .left
        label.numberOfLines = 3
        label.font = UIFont(name: "Helvetica-Bold", size: 22)
        return label
    }()

    override func viewDidLoad() {
        /** Add theLabel to the ViewControllers view */
        view.addSubview(theLabel)
    }

    override func viewDidLayoutSubviews() {
        /* Set the frame when the layout is changed */
        theLabel.frame = CGRect(x: 0,
                                y: 0,
                                width: view.frame.width - 30,
                                height: 24)
    }
}

请注意,theLabel只要在VC中使用功能,仍可以更改其属性。您只需在闭包内部设置各种默认值,并最大程度地减少诸如viewDidLoad()


漂亮的技术...但是在Xcode 9.4.1中它对我不起作用...除非我在计算值的某处指定框架,无论是在构造函数(UILabel(frame:))还是块(label.frame=)的其他地方。框架的任何后续设置(例如中的viewDidLayoutSubviews())都会导致标签不显示。
格伦

2

快速创建标签4

 let label = UILabel(frame: CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.size.width, height: 50))
    label.textAlignment = .center
    label.text = "Hello this my label"

    //To set the color
    label.backgroundColor = UIColor.white
    label.textColor = UIColor.black

    //To set the font Dynamic
    label.font = UIFont(name: "Helvetica-Regular", size: 20.0)

    //To set the system font
    label.font = UIFont.systemFont(ofSize: 20.0)

    //To display multiple lines
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping //Wrap the word of label
    label.lineBreakMode = .byCharWrapping //Wrap the charactor of label

    label.sizeToFit()
    self.view.addSubview(label)

1

Swift 4.2和Xcode10。在ViewController中的某个位置:

private lazy var debugInfoLabel: UILabel = {
    let label = UILabel()
    label.textColor = .white
    label.translatesAutoresizingMaskIntoConstraints = false
    yourView.addSubview(label)
    NSLayoutConstraint.activate([
        label.centerXAnchor.constraint(equalTo: suggestionView.centerXAnchor),
        label.centerYAnchor.constraint(equalTo: suggestionView.centerYAnchor, constant: -100),
        label.widthAnchor.constraint(equalToConstant: 120),
        label.heightAnchor.constraint(equalToConstant: 50)])
    return label
}()

...

使用:

debugInfoLabel.text = debugInfo

0
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 285)
label.textAlignment = .center
label.text = "My label"
self.view.addSubview(label)

在ViewDidLoad中尝试上面的代码


0

Swift 4.2和Xcode 10在viewDidLoad之前初始化标签。

lazy var topLeftLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "TopLeft"
    return label
}()

在viewDidLoad中,向视图添加标签并应用约束。

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(topLeftLabel)
    topLeftLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
    topLeftLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.