UITableViewCell中的UIButton标题在重用时会发生变化

时间:2018-01-02 14:20:31

标签: ios uitableview uibutton swift4

我有一个表格视图,其中包含一个由手机通讯录和Facebook好友组成的数据。单元格的按钮标题应为"邀请"如果用户是联系人并且"添加"如果是facebook的朋友。

但是,每个按钮上的标题都是错误的,并且在滚动时交换。

这是我的模特:

struct MyContact {
   var name: String
   var phone: String
   var photoUrl: String
   var isFBUser: Bool
}

模型数组

var myContacts = [MyContact]()

cellForRowAt

func tableView(_ tableView: UITableView, cellForRowAt indexpath: Indexpath)  -> UITableviewCell {

   let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ContactCell

   let contact = myContacts[indexPath.row]

   if contact.isFBUser == true {
      cell.button.setTitle("Add", for: .normal)
   } else {
      cell.button.setTitle("Invite", for: .normal)
   }

   cell.contact = contact
   cell.configureCell()
}

ContactCell.swift

func configureCell() {
   if contact.isFBUser == true {
      button.setTitle("Add", for: .normal)
   } else {
      button.setTitle("Invite", for: .normal)
   }
}

我甚至尝试在prepareForReuse上将按钮标题设置为nil

override func prepareForReuse() {
  super.prepareForReuse      

   button.setTitle(nil, for: .normal)
}

1 个答案:

答案 0 :(得分:0)

重复使用单元格对象,因此当您将它们出列(或将其传递给configureCell()时)时,您需要继续设置它们的联系属性