大家好,我是 Swift 的新手,我在网上搜索了很长时间。但是没有用。请帮助或尝试提供一些想法如何实现这一目标。
this first pic when I didn't do anything
The Second Pic is when I already select one textfield
The Third Pic is when I selected that selected All Btn
The Four Pic is when I selected that select All Btn and Deselect one textfield
现在我只能像图二和图三那样做,但是当我选择时我不能使图二的文本字段文本颜色。
我怎样才能像图四一样做到这一点?
我正在使用 collectionView 这样做 我尝试了多种变体,但似乎都不起作用。有什么想法吗?
这是我的代码
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MyCollectionViewCell
if isselectAll == true{
cell.titleText2.textColor = .white
cell.titleText2.backgroundColor = UIColor(red: 153/255, green: 31/255, blue: 37/255, alpha: 1)
selectedCell.append(indexPath)
}
return cell
}
func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath)
{
let cell = collectionView.cellForItem(at: indexPath)!
selectedCell.append(indexPath)
cell.contentView.backgroundColor = UIColor(red: 153/255, green: 31/255, blue: 37/255, alpha: 1)
}
func collectionView(_ collectionView: UICollectionView,didDeselectItemAt indexPath: IndexPath)
{
let cell = collectionView.cellForItem(at: indexPath)!
if selectedCell.contains(indexPath) {
selectedCell.remove(at: selectedCell.index(of: indexPath)!)
cell.contentView.backgroundColor = .clear
}
想知道这样做是否是好的做法,最好的方法是什么?谢谢伙伴
最佳答案
使用此代码(还设置文本字段委托(delegate) Storyboard)
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {
@IBOutlet weak var collectedView: UICollectionView!
var flag = false
override func viewDidLoad() {
super.viewDidLoad()
self.collectedView.delegate = self
self.collectedView.dataSource = self
}
//press selected All Button
@IBAction func selcetedAll(_ sender: Any) {
self.flag = true
self.collectedView.reloadData()
}
//MARK: UIcolletionViewDelegate
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10 //return cell according to your requirement
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MyCollectionViewCell
if flag {
cell.textF.backgroundColor = UIColor.red
}
cell.textF.text = String(indexPath.row)
return cell
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.backgroundColor == UIColor.red {
textField.backgroundColor = UIColor.white
} else {
textField.backgroundColor = UIColor.red
}
}
}
关于Swift 如何在选择时更改 CollectionView UItextField backgroundColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41823104/