【问题标题】:how to print text from textField in label programmatically swift如何以编程方式快速从标签中的textField打印文本
【发布时间】:2017-03-05 10:01:57
【问题描述】:

我喜欢通过单击按钮键在标签中打印 textField 值。但我一直无法做到。下面是代码

import UIKit

class MainViewController: UIViewController {


 override func viewDidLoad() {

super.viewDidLoad()


view.backgroundColor = UIColor.gray
setupLabel()
setupTextField()
setupButton()
}

func setupLabel() {

let label = UILabel()
label.frame = CGRect(x: 40, y: 80, width: 300, height: 60)
label.text = "welcome to my world"
label.textColor = UIColor.yellow
label.font = UIFont.boldSystemFont(ofSize: 25)
label.textAlignment = .center
label.layer.borderWidth = 2
label.layer.borderColor = UIColor.yellow.cgColor
label.layer.cornerRadius = 5
view.addSubview(label)
}

func setupTextField() {

let textField = UITextField()
textField.frame = CGRect(x: 10, y: 200, width:   self.view.frame.size.width - 20, height: 60)
textField.placeholder = "text here"
textField.textAlignment = .center
textField.font = UIFont.systemFont(ofSize: 25)
textField.layer.borderWidth = 2
textField.layer.borderColor = UIColor.yellow.cgColor
textField.layer.cornerRadius = 5
view.addSubview(textField)
 }

 func setupButton() {

let button = UIButton()
button.frame = CGRect(x: 50, y: 300, width: self.view.frame.size.width - 100, height: 60)
button.setTitle("Enter", for: .normal)
button.setTitleColor(UIColor.yellow, for: .normal)
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.yellow.cgColor
button.layer.cornerRadius = 5
button.addTarget(self, action: #selector(buttonTarget), for: .touchUpInside)
view.addSubview(button)
  }

  func buttonTarget() {


// i  missed of here

  }
}

【问题讨论】:

    标签: ios swift swift3


    【解决方案1】:

    在这里你需要遵循两个步骤

    您需要在全局而非实例中创建标签和文本字段,例如

    class MainViewController: UIViewController
      let label = UILabel()
      let textField = UITextField()
    

    隐藏分配的实例值

      func setupLabel() {
    
    //let label = UILabel()
    label.frame = CGRect(x: 40, y: 80, width: 300, height: 60)
    label.text = "welcome to my world"
    label.textColor = UIColor.yellow
    label.font = UIFont.boldSystemFont(ofSize: 25)
    label.textAlignment = .center
    label.layer.borderWidth = 2
    label.layer.borderColor = UIColor.yellow.cgColor
    label.layer.cornerRadius = 5
    view.addSubview(label)
    }
    

    然后你可以直接在你的类中的任何地方访问该值

    func buttonTarget() {
    
     if let text = textField.text
        {
            label.text = text
        }
    
    }
    

    【讨论】:

    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多