swift自定義UITableViewCell,並配置到UITableView的注意事項


情況一:直接新建UITableviewController的情況,這里命名為DiaryTableView.swift

1,刪除初始化方法init

2,新建完成后,系統會自動生成很多方法,在UITableView后面帶有“ ?”,一律改成“ !”(這里使測試版本的一個不好的地方,估計以后也會有所修改)

3,新建User Interface/Empty,這里命名為DiaryCell.xib,設置identifier,這里我設置成“DiaryCell”(可以自定義名字,這個很重要,在右上角部位設置)

  新建swift繼承UITableViewCell,這里命名為DiaryCell.swift

  通過設置DiaryCell.xib的custom Class為TestCell關聯.xib和.swift,並按照你自己的需求關聯相關控件(也可以不用關聯控件就可以看到效果)

4,回到DiaryTableView.swift,修改下面三個方法,原因下面的注釋應該足夠詳細了,這里不多說了,這樣運行結果就該出來了

附上核心代碼:

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
        //cell標志符,使cell能夠重用(如果不需要重用,是不是可以有更簡單的配置方法?)
        let indentifier:String = "DiaryCell"
        //注冊自定義cell到tableview中,並設置cell標識符為indentifier(nibName對應UItableviewcell xib的名字)
        var nib:UINib = UINib(nibName:"DiaryCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: indentifier)
        //從tableview中獲取標識符為papercell的cell
        var cell:DiaryCell = tableView.dequeueReusableCellWithIdentifier(indentifier) as DiaryCell
        //設置單元格屬性
        return cell
    }

 

 

情況二:在UIViewController中添加UITableview(稍后播出)

1,設置tableviewcell同上

2,初始化UItableview,並設置frame,並self.view.addSubview(tableview)

3,設置代理delegate,dataSource,實現3個必需的代理方法

附上代碼:

   override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.tableview.delegate = self
        self.tableview.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
        return 1
    }
    
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
        //cell標志符,使cell能夠重用(如果不需要重用,是不是可以有更簡單的配置方法?)
        let indentifier:String = "SwitchCell"
        //注冊自定義cell到tableview中,並設置cell標識符為indentifier(nibName對應UItableviewcell xib的名字)
        var nib:UINib = UINib(nibName:"SwitchCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: indentifier)
        //從tableview中獲取標識符為papercell的cell
        var cell:SwitchCell = tableView.dequeueReusableCellWithIdentifier(indentifier) as SwitchCell
        return cell
    }

    func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat{
        return 40
    }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM