29,029
社区成员
发帖
与我相关
我的任务
分享
protocol ReachabilityDelegate: class, NSObjectProtocol{
func WhetherHaveReachability(reachability: Reachability)
}
class ViewController: UIViewController {
var delegate: ReachabilityDelegate!
override func viewDidLoad() {
super.viewDidLoad()
self.setupReachability()
}
func setupReachability() {
if self.delegate.respondsToSelector("WhetherHaveReachability:") {
self.delegate.WhetherHaveReachability(reachability)
}
}
}
// The protocol to delegate the
// button tap to the ViewController
protocol ButtonDelegate {
func onButtonTap(sender: UIButton)
}
class ViewWithTextAndButton: UIView {
// keeping track of the delegate to use later
weak var delegate: ButtonDelegate?
func onButtonTap(sender: UIButton) {
// invoking the delegate when the
// button is actually tapped
delegate?.onButtonTap(sender)
}
}
class MyViewController: UIViewController, ButtonDelegate {
let viewWithTextAndButton = ViewWithTextAndButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
override func viewDidLoad() {
super.viewDidLoad()
// assigning the delegate
viewWithTextAndButton.delegate = self
view.addSubview(viewWithTextAndButton)
}
// MARK: ButtonDelegate
// the delegated logic is here
func onButtonTap(sender: UIButton) {
print("This button was clicked in the subview!")
}
}
protocol ReachabilityDelegate: class, NSObjectProtocol{
func WhetherHaveReachability(reachability: Reachability)
}
然后就是在ViewController里面定义:
class ViewController: UIViewController {
var delegate: ReachabilityDelegate!
override func viewDidLoad() {
super.viewDidLoad()
self.setupReachability()
}
func setupReachability() {
if self.delegate.respondsToSelector("WhetherHaveReachability:") {
self.delegate.WhetherHaveReachability(reachability)
}
}
}
这样写确实有错误,因为delegate还是为nil的时候,就运行了setupReachability()方法。。。或许我该在viewDidLoad() 里面self.setupReachability()之前先在这个ViewController里面实现定义的delegate?例如:
protocol ReachabilityDelegate: class, NSObjectProtocol{
func WhetherHaveReachability(reachability: Reachability)
}
class ViewController: UIViewController,ReachabilityDelegate {
var delegate: ReachabilityDelegate!
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
self.setupReachability()
}
func setupReachability() {
if self.delegate.respondsToSelector("WhetherHaveReachability:") {
self.delegate.WhetherHaveReachability(reachability)
}
}
func WhetherHaveReachability(reachability: Reachability){
//实现delegate方法
}
}
但是这样写还有一个问题,就是其他controller使用不了这个delegate。。。怎么办怎么办?