2017-03-05 47 views
0

我喜欢通过单击按钮键在标签中打印textField值。但我一直无法做到。下面是代码如何从textField以标签的方式打印文本swift

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 

    } 
} 

回答

0

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

你需要创建在全球范围内不是实例的标签和文本字段,用于如

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 
    } 

} 
+0

hellow哥哥请到这个链接来帮助我https://stackoverflow.com/questions/48970198/how-to-detect-one-button -in-的tableview小区/ 48971060#48971060 –