swift編第5期:UItableView,OCとSwiftの相互調整

2178 ワード

まずUItableViewの簡単な作成を書きましょう.前の号の内容を経て、よく使われるコントロールを作成するのも簡単ですよ.
 
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSURLConnectionDataDelegate {
    
    var dataArray = NSMutableArray()
    var tableView: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.title = "swh"
        
        for var i = 0; i < 6; i++ {
            self.dataArray.addObject("row\(i)")
        }
        
        self.tableView = UITableView(frame: self.view.bounds, style: .Plain)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        self.view.addSubview(self.tableView!)
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentify = "myCellIdentify"
        var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentify) as? UITableViewCell
        if (cell == nil) {
            cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentify)
        }
        var string = self.dataArray.objectAtIndex(indexPath.row) as? String
        cell?.textLabel?.text = string
        
        return cell!
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

そしてSwiftでO-Cコードを呼び出すことで、多くのO-Cの3つのオープンソースライブラリを利用することができます.
プロジェクトでOCクラスのファイルを新しく作成しました.Swiftとのブリッジを作成するかどうかを提示します.YESを選択すると、「プロジェクト名-Bridging-Header.h」というファイルが新しく作成されます.呼び出したいO-Cヘッダファイルをインポートすればいいですよ.
それからO-C呼び出しSwiftコードを紹介して、これはあまりよく使われていないような気がします.
ヘッダーファイルを直接インポートすることです.名前は「プロジェクト名-Swift.h」です.もちろん、名前は必ずしも正しいとは限りません.設定に関連するproduct Module Nameを見て、プロジェクト名を置き換えることができます.
まあ、基本的にはこれでしょうが、実は私たちはswift.hの中で関連するコードの変換を見に行きます