Come creare UILabel a livello di programmazione utilizzando Swift?


115

Come faccio a creare un UILabelprogramma in modo programmatico utilizzando Swift in Xcode 6?

Ho iniziato con una nuova "Applicazione a visualizzazione singola" in Xcode 6 e ho selezionato Swift per questo progetto. Ho i miei file AppDelegate.swifte ViewController.swiftnon sono sicuro di cosa fare da qui.


1
Ti suggerisco di iniziare il tuo studio qui: Documentazione rapida e di arrivare ai tutorial Raywenderlich
Prashant

Risposte:


252
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)
}  

Aggiornamento 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
Non è necessario dichiararlo implicitamente come UILabel, è dedotto da UILabel ()
CW0007007

5
Non dovresti codificare la cornice delle etichette: cosa succede quando il testo cambia o il testo viene localizzato e cambia il numero di caratteri?
Zorayr

Puoi anche controllare questo blog che descrive l'aggiunta programmatica di UITextField, UITextView e UILabel: webindream.com/how-to-change-ui-elements-programmaticamente
farhad rubel

@ iSuresh come fai a sapere che CGPoint (x: 160, y: 285) sarà il centro del modello che stanno usando?
Dave G

2
@rommex Per farlo, chiama label.sizeToFit () .
Josh Wolff

27

Ecco il codice corretto per Swift 3, con commenti a scopo didattico:

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

Grazie Gourav - spero abbia aiutato
Gene Loparco

14

Solo per aggiungere alle già ottime risposte, potresti voler aggiungere più etichette al tuo progetto, quindi fare tutto questo (impostare le dimensioni, lo stile, ecc.) Sarà un problema. Per risolvere questo problema, puoi creare una classe UILabel separata.

  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

    }

}

Per usarlo, procedi come segue

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


}

Proprio quello che stavo cercando!
madprogramer

Grazie amico, ho una domanda, se voglio passare una stringa self.textall'interno di una classe per iniziare in questo modo:myLabel = MyLabel(string: "text")
Daniel Beltrami

Ho appena scoperto come, usando la tua classe e chiamando in questo modo:myLabel.text = "text"
Daniel Beltrami

11

Swift 4.X e 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)

Se hai più etichette nella tua classe, usa l'estensione per aggiungere proprietà.

//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

Puoi creare un'etichetta utilizzando il codice sottostante. Aggiornato.

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

Un altro codice 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)

5

Un'alternativa che utilizza una chiusura per separare il codice in qualcosa di un po 'più ordinato usando 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)
    }
}

Come nota, gli attributi per theLabelpossono ancora essere modificati ogni volta che si utilizzano funzioni nel VC. Stai solo impostando vari valori predefiniti all'interno della chiusura e riducendo al minimo il disordine in funzioni comeviewDidLoad()


Bella tecnica ... ma non funziona per me in Xcode 9.4.1 ... a meno che non specifichi il frame da qualche parte nel valore calcolato, sia nel costruttore ( UILabel(frame:)) che altrove nel block ( label.frame=). Qualsiasi impostazione successiva della cornice (ad esempio in viewDidLayoutSubviews()) faceva sì che l'etichetta non apparisse.
Glenn

5

Crea la UILabelvista fuori dalla viewDidLoadclasse e poi aggiungi quella vista alla tua vista principale nel viewDidLoadmetodo.

lazy var myLabel: UILabel = {


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

E poi aggiungere che viewinviewDidLoad()

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, puoi spiegare il tuo codice. [lazy var myLabel: UILabel = {} ()]. Sarà molto utile. Grazie ....
iOS

1
@iOS Quando crei una variabile in lazy var variable_name = ""quanto non consumerà la tua memoria a meno che quella variabile non venga chiamata dalla tua app. Se quella proprietà non viene utilizzata, non verrà mai eseguita.
I Love Coding

Quindi creeremo tutte le variabili come pigre nel nostro progetto per prestazioni migliori. Ho ragione?
iOS

@iOS yeah! Usa meglio quel tipo di variabile nella tua app per prestazioni migliori. Inoltre, dovresti essere in grado di conoscere anche Thread per prestazioni migliori.
I Love Coding

3

Crea etichetta in swift 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 e Xcode 10. Da qualche parte in 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
}()

...

usando:

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)

Prova il codice sopra in ViewDidLoad


0

Swift 4.2 e Xcode 10 Inizializzano l'etichetta prima di viewDidLoad.

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

In viewDidLoad aggiungi un'etichetta alla vista e applica i vincoli.

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
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.