Swift 4.0 学习笔记一
2017-11-02 本文已影响28人
脚踏实地的小C
最近公司没什么项目弄,Swift越来越多人用了,就自己把以前用OC写的项目用Swift语言写下,小小记录下。
一、获取某个控件的最大Y坐标:
OC中是:
CGRectGetMaxX(某某控件.frame)
而Swift中是:
某某控件.frame.maxY
二、符号运算:
Swift的符号运算不算OC那么的包容,得转成同种类型的才行,举个例子,当你用Int类型的数加Float类型的数,如下例子
let numOne = 11;
let numTwo = 1.1;
let total = numOne + numTwo;
它肯定给你报 Binary operator '+' cannot be applied to operands of type 'Int' and 'Double',因为numOne是Int类型,而numTwo是Double类型。这个时候你如果想得到double类型的数据,那么你只要把numOne转为double类型就可以了。
OC中是:
total = (Double)numOne + numTwo;
但Swift中是:
total = Double(numOne) + numTwo;
三、模型的创建:
创建NSObject类型的swift文件,代码大致如下:
import UIKit
class SCInquireDataModel: NSObject {
var testStr = String();
override init() {//不可缺少的
super.init()
}
}
一开始我忘了写 override init(),一直报错,提示的又是些乱七八糟的,后面才发现忘记实现这个方法。
四、懒加载的实现:
使用:lazy var xxx:type = {}(),例子如下
/** 懒加载*/
lazy var firstLabel:UILabel = {
let tempLabel = UILabel(frame: CGRect(x: 10, y: 5, width: kScreenWidth/3, height: 50));
tempLabel.numberOfLines = 0;
tempLabel.font = UIFont.systemFont(ofSize: 13);
self.addSubview(tempLabel);
return tempLabel;
}()
五、简单宏的实现:
1.创建Swift文件,选择iOS->Source->Swift File

2.将Foundation改为UIKit
3.设置宏定义

有关宏定义的想了解更多的可以看swift下实现宏定义及DEBUG中使用自定义Log、swift中的宏定义
六、UITableView纯代码实现:
1.懒加载创建UITableView
//懒加载
lazy var dataTableView = { () -> UITableView in
let tempTableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.plain);
tempTableView.delegate = self;
tempTableView.dataSource = self;
tempTableView.rowHeight = 60;
self.view.addSubview(tempTableView);
let view = UIView();
tempTableView.tableFooterView = view;
tempTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell");
return tempTableView;
}()
2.实现UITableViewDataSource代理协议
/**
UITableViewDataSource
*/
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!;
cell.textLabel?.text = String(indexPath.row);
return cell;
}
因为是想到哪,就写到哪,所以有点乱,今天暂时就写到这,后面继续摸索!!!