一、對 NSNotification.Name使用Extension
在swif3.0中使用通知,創建名稱時需要是NSNotification.Name
類型,如下發送通知和接收通知
//發送通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "test"), object: nil)
//接收通知
NotificationCenter.default.addObserver(self, selector: #selector(test), name: NSNotification.Name(rawValue: "test"), object: nil)
這樣寫很麻煩,下面我們通過使用Extension
讓書寫時更簡單一些,代碼如下:
extension Notification.Name {
public struct UserInfo {
//用戶登錄成功處理
public static let userLogin = Notification.Name(rawValue: "notification.name.userLogin")
//用戶退出登錄處理
public static let userLogout = Notification.Name(rawValue: "notification.name.userLogout")
//用戶被強制退出登錄處理
public static let userForceLogout = Notification.Name(rawValue: "notification.name.userForceLogout")
}
}
通過在Notification.Name
中添加一個struct
,這樣在調用的時候直接使用點語法,如下:
NotificationCenter.default.post(name: Notification.Name.UserInfo.userLogin, object: nil)
//接收
NotificationCenter.default.addObserver(self, selector: #selector(test), name: Notification.Name.UserInfo.userLogin, object: nil)
二、對UIStoryboard進行Extension
平常使用storyboard
獲取一個viewcontroller
時
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "TestViewController")
通過同樣的思想,在UIStoryboard
中添加一個struct
,更加方便的調用
extension UIStoryboard{
public struct Sbname{
//main
public static let main = UIStoryboard(name: "Main", bundle: nil)
}
}
在調用的時候就可以這樣寫了
let vc = UIStoryboard.Sbname.main.instantiateViewController(withIdentifier: "TestViewController")
三、更多Extension...
extension String {
var floatValue: Float {
return (self as NSString).floatValue
}
func subString(start:Int,length:Int = -1) -> String {
var len = length
if len == -1 {
len = self.count - start
}
let st = self.index(startIndex, offsetBy: start)
let en = self.index(st, offsetBy: len)
return String(self[st ..< en])
}
}
以同樣的思想,可以對UIColor
,UIFont
等常用類型進行擴展,在此就不一一列舉了。在此拋磚引玉,大家可以在評論處寫寫你是如何擴展的。
注意:轉載請注明iOS小喬 http://www.lxweimin.com/p/ab2f0b7d764a