【发布时间】:2017-05-23 18:49:05
【问题描述】:
假设我在一个集合视图中有 3 个单元格。单元格内部是一个关注按钮,其中isSelected = true 状态的标题为following,isSelected = false 状态的文本为follow。
第一个和第三个按钮的isSelected 状态为false,第二个按钮的isSelected 状态为true。这让它变得虚假、真实、虚假。
问题是,我想在重新加载集合视图时保持这些状态。每当我在 collectionView 中调用 pull 来刷新时,它都会读取 json 并将数据加载到 collectionView 中。由于单元格的重用方式,它最终会重新加载前一个单元格。
所以最初,isSelected 状态的顺序是 false、true、false。然后,由于单元格的重用方式,这将变为 false、false true。
然后,一旦我再次请求检查按钮的状态,它就会变回 false、true、false。但是,我想保持状态而不是检查状态。否则,它看起来有问题。一瞬间,按钮的isSelected 状态不正确。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UserCell.reuseIdentifier, for: indexPath) as! UserCell
cell.user = user?[indexPath.row]
// cell.followButton.isSelected = false
return cell
}
.
class UserCell: UICollectionViewCell {
var user: User? {
didSet {
followButton.user = user
}
lazy var followButton: FollowButton = {
let button = FollowButton()
return button
}()
}
.
class FollowButton: UIButton {
var user: User? {
didSet {
checkIfUserIsFollowed()
}
}
override var isSelected: Bool {
didSet {
self.layer.backgroundColor = isSelected ? UIColor.rgb(50, green: 205, blue: 50).cgColor
: UIColor.white.cgColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
layer.cornerRadius = 4
layer.backgroundColor = UIColor.white.cgColor
translatesAutoresizingMaskIntoConstraints = false
setTitle("Follow", for: .normal)
setTitle("Following", for: .selected)
contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)
titleLabel?.font = UIFont(name: "HelveticaNeue", size: 13.0)
contentHorizontalAlignment = .right
setTitleColor(UIColor.rgb(50, green: 205, blue: 50), for: .normal)
setTitleColor(UIColor.white, for: .selected)
layer.borderWidth = 0.5
layer.borderColor = UIColor.rgb(50, green: 205, blue: 50).cgColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func checkIfUserIsFollowed() {
// This is a request that checks where the logged in user is following the user inside the cell. It either returns true or false and sets the state accordingly
}
}
【问题讨论】:
-
你能提供你的
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell方法的实现吗? -
@TarasChernyshenko 完成
标签: swift uitableview uicollectionview uicollectionviewcell tableviewcell