Swift UITableViewCell中的按钮点击事件

今天在做一个demo,就是我通过点击UITableViewCell中的一个按钮,然后跳转到另一个界面,原作者的做法是直接在ViewController中完成这个Action,我认为这是不妥的,首先是分装性不够,其次是无法处理单一的事件(或许每个cell对这个的button的需求不同),因此我对事件进行了封装,给UITableViewCell写了一个扩展来获取当前的UIViewController,代码如下:

extension UITableViewCell {
    func getCurrentViewController()-> UIViewController? {
        let window = UIApplication.sharedApplication().keyWindow
        let navigationController = window?.rootViewController
        if navigationController is UINavigationController {
            let navigation = navigationController as! UINavigationController
            return navigation.topViewController!
        }
        return nil
     }
}

这段代码的缺陷就是我这里只判断了UINavigationController,其他的类型请各位根据自己的情况来添加。
然后通过这个来执行下面的代码:

extension VideoCell {
    func presentViewController() {
        let currentController = getCurrentViewController()
        currentController?.presentViewController(self.playViewController, animated: true, completion: {
            self.playViewController.player?.play()
        })
    }
}

至于为什么我选择在UITableViewCell中进行界面的跳转,是参考了sunnyxx的SelfManager思想,使Cell的封装性更强,扩展中加功能是为了不破坏原来的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值