tableview中的背景按钮图像

时间:2017-08-26 11:45:04

标签: ios swift

我有带有图像数组的tableView。但是当我滚动我的tableView时,按钮中的一些图像会变为另一个。它的发生是因为我使用了这一行:button?.tag = indexPath.row。如何使用这一行并修复它?

完整代码:

let array = ["","","","","","",""]
let arrayI = ["image1.png","image2.png","image3.png","image4.png","image5.png","image6.png","image7.png"]

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return array.count
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: String(format: "cell", indexPath.row), for: indexPath)

        let button = self.view.viewWithTag(1) as? UIButton
        button?.tag = indexPath.row

        button?.setBackgroundImage(UIImage(named: arrayI[indexPath.row]), for: .normal)

        cell.selectionStyle = .none

        return cell
    }

1 个答案:

答案 0 :(得分:1)

请按照步骤加载带自定义单元格的表格视图

步骤1:创建自定义UITableviewCell类,在此类中设计您的单元格。

第2步:在视图控制器的viewDidLoad中为您的UITableView注册该单元格。

self.tblView.register(UINib(nibName: "customTableCell", bundle: nil), forCellReuseIdentifier: "customTableCell")

第3步:编写tableview委托方法

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrayData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "customTableCell", for: indexPath) as! customTableCell
    cell.button?.setBackgroundImage(UIImage(named: arrayData[indexPath.row]), for: .normal)
    return cell
}

注意:请勿忘记提供数据源并将tableview的连接委派给XIB中的文件所有者。

希望这会有所帮助。

相关问题