【问题标题】:UIButton title inside UITableViewCell changes on reuseUITableViewCell 中的 UIButton 标题在重用时发生变化
【发布时间】:2018-01-02 14:20:30
【问题描述】:

我有一个表格视图,其中包含由电话联系人和 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)
}

【问题讨论】:

  • 您的代码似乎是正确的,但您能确定一下CellForRowAtIndex 吗?在调用configureCell() 之前,您是否在单元格上设置了contact?还有,按钮是怎么创建的?
  • 我已经更新了我的代码。
  • 如果您正在传递一个联系人对象并且您正在调用configureCell() ,那么您不需要制作if contact.isFBUser == true { button.setTitle("Add", for: .normal) } else { button.setTitle("Invite", for: .normal) }
  • dequeueCell 代码?没有“myCell.contact = someArray[indexpath.row]”?你的方法没有返回单元格?
  • 我再次更新了我的代码,对不起。

标签: ios uitableview uibutton swift4


【解决方案1】:

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

【讨论】:

  • 如果您不介意,可以举个例子吗?我很困惑,因为我认为我在 cellForRowAt 中的代码已经在这样做了?无时无刻不在设置属性。
猜你喜欢
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
相关资源
最近更新 更多