加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift - protocol

发布时间:2020-12-14 07:10:00 所属栏目:百科 来源:网络整理
导读:Protocol(协议)用于统一方法和属性的名称,而不实现任何功能。协议能够被类,枚举,结构体实现,满足协议要求的类,枚举,结构体被称为协议的遵循者。 遵循者需要提供协议指定的成员,如属性,方法,操作符,下标等。 这里只讲和oc 代理类似的那种 一. 声明

Protocol(协议)用于统一方法和属性的名称,而不实现任何功能。协议能够被类,枚举,结构体实现,满足协议要求的类,枚举,结构体被称为协议的遵循者。

遵循者需要提供协议指定的成员,如属性,方法,操作符,下标等。

这里只讲和oc 代理类似的那种

一. 声明一个protocol : NSObjectProtocol

protocol GGTableViewControllerDelegate:NSObjectProtocol {
    //方法
    func closeButtonDidClicked()
    func tableViewDidSelectedAtIndexPath(indexPath:NSIndexPath)
}

二. 声明delegate属性

weak var delegate:GGTableViewControllerDelegate?

三. 在合适的地方让delegate 调用代理方法

func closeView() {
    print("close view")
    if ((delegate?.respondsToSelector("closeButtonDidClicked")) != nil) {
        delegate?.closeButtonDidClicked()
    }
}
func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if ((delegate?.respondsToSelector("tableViewDidSelectedAtIndexPath:")) != nil) {
            delegate?.tableViewDidSelectedAtIndexPath(indexPath)
        }
 }

在这里,目前还不知道需不需要像oc一样,在调用之前判断代理是否还存在,是否还响应该方法,也不知道这种格式是否正确,求指点一二

四.遵守代理协议

class MainViewController: UIViewController,GGTableViewControllerDelegate {

    let vc = GGTableViewController()     
    vc.delegate = self
}

五.实现代理方法

//MARK: GGTableViewControllerDelegate
    func closeButtonDidClicked() {
        print("will close")

        let ggView = view.subviews.last
        ggView?.removeFromSuperview()

    }

    func tableViewDidSelectedAtIndexPath(indexPath: NSIndexPath) {
        print(indexPath)
    }


项目源码:https://git.oschina.net/lisForCoding/GGTableViewController.git

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读