嗨,我是斯威夫特的新人,我在网上搜索了很长时间。但没用。请帮助或尝试提供一些如何实现这一点的想法。
当我没有做任何事情时,第一张照片
第二张Pic是我已经选择了一个文本字段
第三张图片是我选择了所有Btn
的时候
我选择了四张Pic,选择All Btn并取消选择一个文本域
现在我只能像Pic 2和Pic Third那样做,但是当我选择时,我无法使Pic两个textField文本颜色。
我怎么能像Pic Four那样做?
我使用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
}
想知道这样做是否是一种好习惯,最好的方法是什么?感谢队友
答案 0 :(得分:1)
使用此代码(也设置文本字段代表来自故事板)
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
}
}
}
答案 1 :(得分:0)
首先,在选择和取消选择时打印出indexPath。检查是否按预期添加和删除了项目。如果没有,那么这一步就有问题了。
如果数组值按预期更改,则意味着视图不会按照您的喜好进行更新,即使是值也是如此。
现在,使用断点并检查您的预期代码是否正在运行。如果是,则意味着您编写的代码行是错误的。如果没有,这意味着你没有在正确的地方写它。
只需运行代码,我就可以给你一个简单的答案。但它无助于您学习调试。做我在上面说的步骤,让我知道会发生什么。
感谢。