我相信大家從OC轉(zhuǎn)到Swift的時(shí)候總會(huì)有這個(gè)困惑“以前在OC這樣用,Swift該怎么寫(xiě)牲证?
多的不說(shuō)了往下看划滋。
1.懶加載
- Objective-C:
-(UITableView *)tableView{
if (_tableView == nil) {
UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
_tableView = tableView;
_tableView.dataSource = self;
_tableView.delegate = self;
_tableView.backgroundColor = [UIColor grayColor];
}
return _tableView;
}
- Swift
在定義時(shí) 增加lazy
關(guān)鍵字
lazy var tableView = UITableView()
也可以這樣
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.frame = self.view.bounds
tableView.backgroundColor = UIColor.black
return tableView
}()
但是不建議使用第二種方法植阴,因?yàn)榈诙N方法本質(zhì)是一個(gè)閉包,使用self.得考慮是否循環(huán)引用粉怕,使用[weak self]
又得考慮解包的問(wèn)題,而且閉包中智能提示不友好所以推薦第一種寫(xiě)法抒巢。
2.重寫(xiě)屬性setter方法
- Objective-C
在用OC開(kāi)發(fā)的時(shí)候經(jīng)常會(huì)重寫(xiě)某個(gè)屬性的setter方法來(lái)給子控件賦值
-(void)setMeMenu:(MeMenu *)meMenu{
_meMenu = meMenu;
self.nameLabel.text = meMenu.name;
self.iconView.image = [UIImage imageNamed:meMenu.iconName];
}
- Swift
在定義屬性時(shí)增加didSet
意思是在屬性set之后執(zhí)行
PS:沒(méi)有智能提示
var meMenu: meMenu?{
didSet{
nameLabel.text = meMenu?.name;
}
}
3.重寫(xiě)frame的setter方法
- Objective-C
在OC開(kāi)發(fā)中大家都有過(guò)重寫(xiě)cell frame的需求
-(void)setFrame:(CGRect)frame
{
frame.origin.y += 10;
frame.size.height -= 10;
[super setFrame:frame];
}
- Swift
override var frame:CGRect{
didSet {
var newFrame = frame
newFrame.origin.x += 10
newFrame.size.width -= 10 * 2
newFrame.origin.y += 10
newFrame.size.height -= 10 * 2
super.frame = newFrame
}
}
4.字典轉(zhuǎn)模型
- Objective-C
@implementation MeMenu
-(instancetype)initWithDic:(NSDictionary *)dic{
self = [super init];
if (self) {
self.iconName = dic[@"icon"];
self.name = dic[@"name"];
}
return self;
}
+(instancetype)initWithDic:(NSDictionary *)dic{
return [[self alloc]initWithDic:dic];
}
+(NSMutableArray *)meMenus{
NSString *path = [[NSBundle mainBundle] pathForResource:@"dataArr" ofType:@"plist"];
NSArray *arr = [NSArray arrayWithContentsOfFile:path];
NSMutableArray *arrs = [NSMutableArray array];
for (NSDictionary *dic in arr) {
[arrs addObject:[MeMenu initWithDic:dic]];
}
return arrs;
}
@end
- Swift
class MeMenu: NSObject {
var name: String?
var type: String?
var detail: String?
var icon: String?
init(dic: [String: String]) {
super.init()
setValuesForKeys(dic)
}
//外面調(diào)用這個(gè)類方法
class func meMenus() -> [Any] {
let arrDic = NSArray(contentsOfFile: Bundle.main.path(forResource: "DoctorList.plist", ofType: nil)!)!
var arrayM = [MeMenu]()
for dic in arrDic {
let doctor = MeMenu(dic: dic as! [String : String])
arrayM.append(doctor)
}
return arrayM
}
}
5.Swift的extension
和convenience
關(guān)鍵字
extension(擴(kuò)展) 就是為一個(gè)已有的類贫贝、結(jié)構(gòu)體、枚舉類型或者協(xié)議類型添加新功能。這包括在沒(méi)有權(quán)限獲取原始源代碼的情況下擴(kuò)展類型的能力(即 逆向建模 )稚晚。擴(kuò)展和 Objective-C 中的Category(分類)類似崇堵。(與 Objective-C 不同的是,Swift 的擴(kuò)展沒(méi)有名字客燕。)
Swift 中的擴(kuò)展可以:
添加計(jì)算型屬性和計(jì)算型類型屬性
定義實(shí)例方法和類型方法
提供新的構(gòu)造器
定義下標(biāo)
定義和使用新的嵌套類型
使一個(gè)已有類型符合某個(gè)協(xié)議
在 Swift 中鸳劳,你甚至可以對(duì)協(xié)議進(jìn)行擴(kuò)展,提供協(xié)議要求的實(shí)現(xiàn)也搓,或者添加額外的功能棍辕,從而可以讓符合協(xié)議的類型擁有這些功能。你可以從協(xié)議擴(kuò)展獲取更多的細(xì)節(jié)还绘。
注意
擴(kuò)展可以為一個(gè)類型添加新的功能楚昭,但是不能重寫(xiě)已有的功能。
-
使用
extension
分割代碼
可以讓代碼更易閱讀與修改
class DempViewController: UIViewController {
lazy var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
// MARK: 設(shè)置界面
extension DempViewController{
fileprivate func setupUI(){
tableView.dataSource = self
tableView.delegate = self
tableView.frame = view.bounds
}
}
// MARK: 表格的數(shù)據(jù)源方法
extension DempViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id", for: indexPath)
return cell
}
}
// MARK: 表格的代理方法
extension DempViewController: UITableViewDelegate{
}
- 使用
convenience
便利構(gòu)造器快速創(chuàng)建控件 - 新建 UIButton+Extension.swift 文件
- 建立 UIButton 的便利構(gòu)造函數(shù)
extension UIButton {
/// 快速創(chuàng)建按鈕
/// - parameter title: title
/// - parameter imageName: imageName
/// - parameter backImageName: backImageName
///
/// - returns: UIButton
convenience init(title: String, imageName: String, backImageName: String) {
self.init()
setTitle(title, for: .normal)
setImage(UIImage(named: imageName), forState: .Normal)
setImage(UIImage(named: imageName + "_highlighted"), forState: .Highlighted)
setBackgroundImage(UIImage(named: backImageName), forState: .Normal)
setBackgroundImage(UIImage(named: backImageName + "_highlighted"), forState: .Highlighted)
}
}
注意:便利構(gòu)造器必須先調(diào)用self.init()
而且沒(méi)有智能提示~
開(kāi)發(fā)中多利用extension
分割代碼拍顷、抽取常用代碼
- Objective-C中的
Category