界面通信
//控制器1
importUIKit
//页面传值1:从前往后传
//页面传值2:(1)闭包传值
//(2)代理传值
classViewController:UIViewController{
letstr ="helloWorld"
overridefuncviewDidLoad() {
super.viewDidLoad()
navigationItem.title="控制器1"
//self写在哪个实例方法里面表示该实例,写在类方法里面表示该类
letrightBtn =UIBarButtonItem(title:"跳转", style: .Plain, target:self, action:"pushToSecond")
navigationItem.rightBarButtonItem= rightBtn
}
//右按钮的响应方法:跳转到第二个页面
func pushToSecond(){
let secondVC=SecondViewController()
secondVC.delegate=self
//属性传值
secondVC.oneStr=str
//实现闭包
secondVC.closure= {
(str:String)->Int
in
print("viewcontroller-value =https://www.it610.com/(str)")
return str.lengthOfBytesUsingEncoding(4)
}
navigationController?.pushViewController(secondVC, animated:true)
}
overridefuncdidReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extensionViewController:secondProtocol{
func translateString(str:String) {
print("协议传值\(str)")
}
}
APPDelegate
@UIApplicationMain
classAppDelegate:UIResponder,UIApplicationDelegate{
//可选类型不能直接参与运算。要运算的话必须进行强制解包
【界面通信】varwindow:UIWindow?
funcapplication(application:UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject:AnyObject]?) ->Bool{
letVC =ViewController()
//创建导航视图控制器
letnavc =UINavigationController(rootViewController: VC)
window=UIWindow(frame:UIScreen.mainScreen().bounds)
window?.backgroundColor=UIColor.whiteColor()
//设置window根视图控制器
window?.rootViewController= navc
window?.makeKeyAndVisible()
returntrue
}
//控制器2
importUIKit
//定义协议
protocol secondProtocol{
func translateString(str:String)
}
class SecondViewController:UIViewController{
//定义一个接收从第一个页面传过来的字符串
var oneStr:String?
//声明一个传值闭包(给传过来的参数进行拼接)
var closure:((str:String)->Int)?
//声明代理
var delegate:secondProtocol?
override func viewDidLoad() {
super.viewDidLoad()
print(oneStr)
navigationItem.title="控制器2"
view.backgroundColor=UIColor.cyanColor()
//定义左边按钮
let leftBtn =UIBarButtonItem(title:"back", style: .Plain, target:self, action:"backAction")
navigationItem.leftBarButtonItem= leftBtn
}
//
func backAction(){
closure!(str:"第二个页面")
delegate?.translateString("secondVC")
navigationController?.popViewControllerAnimated(true)
}
overridefuncdidReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
推荐阅读
- Docker应用:容器间通信与Mariadb数据库主从复制
- Unity和Android通信系列文章2——扩展UnityPlayerActivity
- Android|Android BLE蓝牙连接异常处理
- 界面展示bug随笔
- KubeDL HostNetwork(加速分布式训练通信效率)
- Android|Android Kotlin实现AIDL跨进程通信
- Android|Android USB通信
- ubuntu开机默认进入命令行模式/用户图形界面
- 企业级/B端设计交互/界面规范(二)|企业级/B端设计交互/界面规范(二) 基础原则规范说明
- react组件通信