Swift-- 常用简单封装

作者: 71150ce14a00 | 来源:发表于2017-01-21 15:29 被阅读20次

封装继承多态是大家整体挂载嘴边的东西,但能把这几个做的很好的寥寥无几,今天就谈谈封装

封装就是把一些逻辑复杂或者代码繁多的东西封装起来,让自己调用起来简洁明了。

swift为例子,在view中要对width进行赋值要这样 view.frame.size.width , 每次这么长很烦 你可以封装。

extension UIView{
var db_height:CGFloat{
    set(v){
        self.frame.size.height = v
    }
    get{
        return self.frame.size.height
    }
}

var db_width:CGFloat{
    set(v){
        self.frame.size.width = v
    }
    get{
        return self.frame.size.width
    }
   }
}

这时候你调用的时候 只需要 view.db_width = xxx , 当然能封装的不只是width和height 还有很多属性 ,这里只是打开思维,抛砖引玉

还有的时候 你需要这样的操作,x必须在0,5之间 y在1,10之间 大于 取最大,小于取最小 , 这时候 就需要对算法进行封装。

func DB_CLAP(_value:CGFloat,_ _low:CGFloat,_ _high:CGFloat)->CGFloat{
return _value<_low ? _low: _value>_high ? _high:_value
}

这样封装后 就可以简单的调用 v = DB_CLAP(v,0,5) 这样就可以确保v在0,5之间 ,所有都可以套用

再比如说,iOS中的弹框代码比较冗长,我们也可以进行封装,因为现在的弹框要用到present 必须拿到当前的viewController

//MARK: -得到当前正在显示的vc
func getCurrentVC()->UIViewController?{
var result:UIViewController?
var window = UIApplication.sharedApplication().keyWindow
if window?.windowLevel != UIWindowLevelNormal{
    let windows = UIApplication.sharedApplication().windows
    for tmpWin in windows{
        if tmpWin.windowLevel == UIWindowLevelNormal{
            window = tmpWin
            break
        }
    }
}
 let fromView = window?.subviews[0]
if let nextRespnder = fromView?.nextResponder(){
    if nextRespnder.isKindOfClass(UIViewController){
        result = nextRespnder as? UIViewController
    }else{
        result = window?.rootViewController
    }
}
return result
 }

一般弹框一个或者两个按钮

你可以这样封装

import UIKit

class DBAlert {

static func showAlert(meg:String,btn1:String,btn2:String?,handler:((UIAlertAction) -> Void)?){
    guard let vc = getCurrentVC() else{ return }
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        let alertController = UIAlertController(title:"提示",
            message:meg ,
            preferredStyle: .Alert)
        let cancelAction = UIAlertAction(title:btn1, style: .Cancel, handler:nil)

        alertController.addAction(cancelAction)

        if btn2 != nil{
            let settingsAction = UIAlertAction(title: btn2, style: .Default, handler: { (action) -> Void in
                handler?(action)
            })
            alertController.addAction(settingsAction)
        }
        vc.presentViewController(alertController, animated: true, completion: nil)
    })
}

static func showAlert(meg:String){
    showAlert(meg, btn1: "确定", btn2: nil, handler: nil)
}

}

这时候 不管哪个页面需要弹框的时候 就不用那个冗长的代码了,只需要简单的这样

//一个按钮的
DBAlert.showAlert("这是个提示")

//两个按钮的
DBAlert.showAlert("两个按钮的提示", btn1: "取消", btn2: "确定") { (action) -> Void in
    //确定执行的事件
}

这样是不是感觉代码就很清爽了。

相关文章

网友评论

    本文标题:Swift-- 常用简单封装

    本文链接:https://www.haomeiwen.com/subject/lwxnbttx.html