swift 2016.9.23: 已經(jīng)更新到 Swift 3.0
從2014年發(fā)布以來Swift每年變化還是挺大的遭铺,但是隨著Swift的使用者越來越多很有必要研究一下了。
我認(rèn)為IOS編程很大程度上就是TableView編程毁习,在App中各種TableView無所不有撇他,所以我就已簡單的Swift TableiView和Swift Objective混編簡單入門一下swift肥印。
首先在ViewController中申明一個TableView性锭,然后把它加載到view上。
注意此處tableiView初始化在屬性中,而不用卸載method中招驴。
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
{
let tableView = UITableView(frame:CGRect(x:0,y:0,width:UIScreen.main.bounds.size.width,
height:UIScreen.main.bounds.size.height) ,
style: UITableViewStyle.plain)
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = UIColor.clear
self.view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = MyCell().customCell(tableView: tableView)
cell.loadData(line: indexPath.row, title: "title" + String(indexPath.row))
print(Unmanaged.passUnretained(cell).toOpaque());
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let oc = OCViewController()
self.navigationController?.pushViewController(oc, animated: true)
}
func provide(person:String) -> String {
return "hello"
}
自定義Cell
此處我有一個疑問篙程,在oc中NSStringFromClass可以很好的給cell設(shè)置標(biāo)示,而在Swift中沒有類似的方法别厘,看到網(wǎng)上有人說String.self()方法房午,但似乎不起作用,歡迎大家評論留言
import UIKit
class MyCell: UITableViewCell {
@IBOutlet weak var iTitleLabel: UILabel!
@IBOutlet weak var iOrderLabel: UILabel!
func customCell(tableView:UITableView) -> MyCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "MyCell")
if cell == nil{
cell = Bundle.main.loadNibNamed("MyCell", owner: nil, options: nil)?.last as! MyCell?
}
return cell as! MyCell
}
func loadData(line:Int,title:String) {
iOrderLabel.text =? String(line)
iTitleLabel.text = title
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.1)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Swift與Objective的混編
在Swift的工程中新建Objective類丹允,和橋接文件“工程名-Bridging-Header.h”
在橋接文件中引入oc頭文件
#import "OCViewController.h"
在oc類文件中條用Swift類需引入Swift默認(rèn)透頭文件“工程名-swift.h”
完整項目見gitHub:
https://github.com/393698063/SwiftAndObjectiveTableview