视图之间传值有几种方式,今天暂时写一下代理传值 ,后更新
开发平台 : mac 10.10.2
编译器 :xcode6.3(6D532l)
运行平台 : xcode iphone 5s虚拟机
所谓代理传值,就是通过delegate 来实现。设置两个视图.通过代理把第二张的视图的某值传给第一张视图
UI如图。给第二章视图创建并绑定一个类
在第二个视图类里声明一个协议
因为之前写的是一个测试,所以命名还是有点坑的 protocol channelProtocol{ func onChangChannel(channelNumber:Int) }
在第二个视图类里添加协议的代理
var delegate:channelProtocol?
delegate?.onChangChannel(rowOfTable) //rowOfTable 之前声明的便变量
第二个视图类的完整代码为
import UIKit import AVFoundation class ViewController: UIViewController,channelProtocol { @IBOutlet weak var label: UILabel! var audioPlayer : AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) { var ChanleC:secondView = segue.destinationViewController as! secondView ChanleC.delegate = self } func onChangChannel(channelNumber: Int) { label.text = "\(channelNumber)" } }
下面开始写ViewControler 类
加入刚刚在视图二绑定类声明的协议 。实现方法
class ViewController: UIViewController,channelProtocol { }
重写 prepareForSegue(segue: UIStoryboardSegue ,sender: AnyObject ?) 方法,这个也是代理传值的重点
overridce func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) { var ChanleC:secondView = segue.destinationViewController as! secondView ChanleC.delegate = self }
实现协议的方法
func onChangChannel(channelNumber: Int) { label.text = "\(channelNumber)" }
ViewController.swift完整代码是
import UIKit class ViewController: UIViewController,sender: AnyObject?) { var ChanleC:secondView = segue.destinationViewController as! secondView ChanleC.delegate = self } func onChangChannel(channelNumber: Int) { label.text = "\(channelNumber)" } }
完整项目代码托管到codinghttps://coding.net/goooooooofy/delegateGetValue.git
更多文章。访问 个人网站 http://www.goofy.ga