我做了一个自定义菜单栏,现在我想为导航实现一个滑块。我将第一个图像设置为selectedItem,其颜色为.white,其他图像设置为.gray ..现在,我想单击其他图像并更改其.tintColor。这是指向整个code
的链接let imageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "Plan")?.withRenderingMode(.alwaysTemplate)
iv.tintColor = UIColor.black
return iv
}()
override var isSelected: Bool {
didSet {
imageView.tintColor = isSelected ? .white : .gray
}
}
override var isHighlighted: Bool {
didSet {
imageView.tintColor = isHighlighted ? .white : .white
}
}
override func setupViews() {
super.setupViews()
addSubview(imageView)
addConstraintsWithFormat("H:[v0(28)]", views: imageView)
addConstraintsWithFormat("V:[v0(28)]", views: imageView)
addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
}
}
我应该能够单击其他图像并在取消选择其他图像的同时更改tintColor。
答案 0 :(得分:0)
我认为collectionView's
cellForItemAt
方法collectionViewCell's
isSelected
中存在一些不一致之处。
在cellForItemAt
中,您正在设置cell.tintColor = .white
在isSelected
中,您正在设置imageView.tintColor = isSelected ? .white : .gray
尝试将cellForItemAt
中的代码更改为
cell.imageView.tintColor = .gray
我已经创建了示例代码,以便您可以识别问题,
class ViewController: UIViewController, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
cell.imageView.tintColor = .gray
return cell
}
}
class CustomCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override var isSelected: Bool {
didSet {
self.imageView.tintColor = isSelected ? .white : .gray
}
}
}