小记:初次使用Swift来创建UI界面,所以记下点实用笔记方便日后学习。
要求:创建两个界面,第一个界面有 Label 和 Button,另一个界面有TextField 和 Button。通过点击Button点击来触发点击事件。使用Block来实现将第二个界面的TextField里的值传到第一个界面的Label里面。
1.ViewController
/**/懒加载label(见名知意--> Lazy)
lazy var lab:(UILabel) = {
let lab = UILabel(frame:CGRectMake(100,100,100,50))
lab.backgroundColor = UIColor.cyanColor()
return lab
}()
/**/懒加载button
lazy var btn:(UIButton) = {
let btn = UIButton(frame:CGRectMake(100,200,100,50))
btn.backgroundColor = UIColor.redColor()
//selector("btnAction:") #selector(btnAction:)
btn.addTarget(self, action:"btnAction:", forControlEvents: UIControlEvents.TouchUpInside)
btn.setTitle("买买买", forState: UIControlState.Normal)
return btn
}()
/**/button点击事件
fun btnAction(btw:UIButton){
let vc = SecondViewController()
vc.closure = {
(str:String)->()
in
self.lab.text = str
}
naviagationContrcoller?.pushViewController(vc, animated: true)
}
2. SecondViewController
/**/ 声明
var closure:((str:String)->())?
/**/懒加载
lazy var tf:(UITextField) = {
let tf = UITextField(frame:CGRectMake(100,150,100,50))
tf.backgroundColor = UIColor.greenColor()
return tf
}()
lazy var btn:(UIButton) = {
let btn = UIButton(frame: CGRectMake(100,280,100,50))
btn.addTarget(self, action: "btnAction:", forControlEvents: UIControlEvents.TouchUpInside)
btn.setTitle("回去", forState: UIControlState.Normal)
btn.backgroundColor = UIColor.blueColor()
return btn
}()
/**/按钮方法
func btnAction(btn:UIButton){
closure!(str: tf.text!)
navigationController?.popViewControllerAnimated(true)
}