1. 程式人生 > >Swift自定義Cell寫表格

Swift自定義Cell寫表格

1.建立model繼承NSObject

  var title:String
    var pic:String
    var title2:String
    init(title:String,pic:String,title2:String) {
        self.title = title
        self.pic = pic
        self.title2 = title2
    }

2.建立表格cell繼承UITableViewCell
用xib

@IBOutlet weak var imgv: UIImageView!
    @IBOutlet weak var lb1: UILabel!
    @IBOutlet weak var lb2: UILabel!
    
    func setCellWithData(md:model) -> Void {
        self.lb1.text = md.title
        self.lb2.text = md.title2
        self.imgv.image = UIImage.init(named: md.pic)
    }

3.寫表格

import UIKit

class oneViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.navigationItem.title = "訊息"
        
        let uiv = UIView.init()
        
        let btn = UIButton.init()
        btn.frame = CGRect(x: 0, y: -20, width: 40, height: 40)
        btn .setImage(UIImage.init(named: "1"), for: UIControl.State.normal)
        uiv .addSubview(btn)
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: uiv)
        
        self.navigationController?.navigationBar.barTintColor = UIColor.cyan
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "➕", style: UIBarButtonItem.Style.done, target: self, action: nil)
        
        let uisb = UISearchBar.init(frame: CGRect(x: 0, y: 90, width: self.view.frame.width, height: 40))
        uisb.placeholder = "請輸入要搜尋的資訊。。。"
        self.view .addSubview(uisb)
        
        let tbv = UITableView.init()
        tbv.frame = CGRect(x: 0, y: 130, width: self.view.frame.width, height: self.view.frame.height-130)
        tbv.delegate = self
        tbv.dataSource = self
        tbv.register(UINib.init(nibName: "MYTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        self.view .addSubview(tbv)
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MYTableViewCell = tableView .dequeueReusableCell(withIdentifier: "cell") as! MYTableViewCell
        
        var arr = ["1","2","3","4","5"]
        var arr2 = ["群1","群2","群3","群4","群5"]
        var arr3 = ["我確認群無","法講課我服了你","愛發科驕傲我發你","按付款就把我放","看見阿爾巴安撫"]
        
        cell.imgv.image = UIImage.init(named: arr[indexPath.row])
        cell.lb1.text = arr2[indexPath.row]
        cell.lb2.text = arr3[indexPath.row]
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }

   

}