swift 中的delegate 写法

前端之家收集整理的这篇文章主要介绍了swift 中的delegate 写法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


1. 声明
// this delegate needs a @objc,because @optional is only for objective-c,not for swift
@objc protocol DetailViewControllerDelegate : NSObjectProtocol {
    optional func changeItem(forUserModel userModel: UserModel?)
}

2.代理的点击事件
    func onChangeButtonClick(sender: UIButton!) {
        if (userModel != nil) {
            userModel!.userName = "ChangeName"
            userModel!.email = "robinson_911@163.com"
            // changeItem needs to add a ? to the end,before (),because
            // this function is optional
            // delegate? 表示可能没有代理,而changeItem?表示方法可能没有实现,这样写就算没有实现也没有问题
            delegate?.changeItem?(forUserModel: userModel)
            self.navigationController!.popViewControllerAnimated(true)
        }
    }
3. 实现
class RootViewController:UITableViewController,DetailViewControllerDelegate{}

    func changeItem(forUserModel userModel: UserModel?) {
        var index = 0
        for index = 0; index < dataSource.count; index++ {
            let model = dataSource[index] as? UserModel
            if model!.userID == userModel!.userID {
                model!.phone = userModel!.phone
                model!.email = userModel!.email
                tableView.reloadRowsAtIndexPaths([currentIndexPath!],withRowAnimation: UITableViewRowAnimation.Fade)
                break
            }
        }
    }
原文链接:https://www.f2er.com/swift/324594.html

猜你在找的Swift相关文章