我做了一个自定义菜单栏,现在我想为导航实现一个滑块。我将第一个图像设置为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。
最佳答案
我认为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
}
}
}
关于ios - 选中后更改imageView的tintColor无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56239038/