欢迎大家评论,问问题,质疑
ViewController.swift
import UIKit
//创建的入口和写UI时的入口是一样的,只不过将语言设置成swift
//遵守协议
class ViewController: UIViewController,SecondViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let button : UIButton = UIButton(type: UIButtonType.System)
button.frame = CGRectMake(100, 200, 50, 50)
button.backgroundColor = UIColor.magentaColor()
button.setTitle("点击", forState: UIControlState.Normal)
button.addTarget(self, action: "action", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
func action(){
let secondVC = SecondViewController()
secondVC.delegate = self
secondVC.sendMessageBlock = {
(a : Int) in
print("block传过来的值\(a)")
}
self.presentViewController(secondVC, animated: true, completion: nil)
}
func getNumber(number: Int) {
print(number)
}
}
SecondViewController.swift
import UIKit
//定义一个不是必须实现的协议(必须有 @objc 和 optional )
@objc protocol SecondViewControllerDelegate {
optional func getNumber(number : Int)
}
//类型命名
typealias block = ((Int)->Void)
class SecondViewController: UIViewController {
//定义一个delegate,类型为SecondViewControllerDelegate
var delegate : SecondViewControllerDelegate?
//定义一个block属性
var sendMessageBlock : block! = nil
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.cyanColor()
//初始化一个Button
let button : UIButton = UIButton(type:UIButtonType.System)
button.frame = CGRectMake(100, 200, 50, 50)
button.backgroundColor = UIColor.redColor()
button.setTitle(“点击”, forState: UIControlState.Normal)
button.addTarget(self, action: “action”, forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
func action(){
//判断?修饰的是否有值
if let a = self.delegate {
print(“111(a)”)
a.getNumber!(1)
}
self.sendMessageBlock(2)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
449




被折叠的 条评论
为什么被折叠?



