IOS的UITableView控件簡單使用

在IOS組件中,UITableView是幾乎每個應用都會使用到的控件,沒有之一。

UITableView簡單使用

 var arr : [String]?

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.arr = ["1","2","3"]
        
        let tableView = UITableView(frame: self.view.bounds,style: UITableView.Style.plain)
        tableView.dataSource = self
        tableView.delegate = self;
        tableView.register(NSClassFromString("UITableViewCell"), forCellReuseIdentifier: "qingcheng")
        self.view.addSubview(tableView)
    }

然後實現 UITableViewDelegate,UITableViewDataSource 兩個協議。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("執行總條數")
        return arr!.count;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "qingcheng",for: indexPath)
        cell.textLabel?.text = "test"
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100;
    }

點擊運行

自定義cell

複雜一點的應用都會自定義一個cell來滿足自己的設計需求

使用xib來實現

創建一個cocoa touch class,勾選xib

在ViewDidLoad的時候,可以需要使用UINib來加載Xib

 let tableView = UITableView(frame: self.view.bounds,style: UITableView.Style.plain)
        tableView.dataSource = self
        tableView.delegate = self;
        tableView.register(UINib.init(nibName: "MyCellTableViewCell", bundle: nil), forCellReuseIdentifier: "qingcheng")
        self.view.addSubview(tableView)

協議實現加載cell的方法也需要做對應的調整


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MyCellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "qingcheng",for: indexPath) as! MyCellTableViewCell
        cell.setName(name: "青城同學")
        return cell
    }

然後點擊運行。

簡單的使用差不多就到這裏了。UITableView是一個非常強大的控件,比如刪除cell,cell排序,機會都可以幾行代碼實現。

歡迎關注我的微信搜索公衆號 【青城同學】,不定時和你分享一些技術和有趣的事情

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章