需求:在一堆選項中選出某一個餐胀,并作出標記麻惶,其它已選的設(shè)為正常距误。
根據(jù)不同的業(yè)務(wù)場景這樣的需求可以采用UICollectionView喇嘱、UItableView茉贡、或直接拖控件(代碼)。
1者铜、代碼或拖控件的一些技巧:
使用一個背景View來承載各個可選擇的子View腔丧。
如下:
image.png
單獨使用一個背景View方便后面整體操作。
@IBAction func clickSelectEvent(_ sender: UIButton) { //所有按鈕的點擊事件都指向該方法
sender.isSelected = !sender.isSelected
if sender.isSelected == false {
return
}
sender.backgroundColor = UIColor.colorWithHex("E96858", alpha: 0.9) //按鈕選中的背景色
selectString = sender.titleLabel?.text ?? "" //把選擇的內(nèi)容傳遞出去
guard let btns = sender.superview?.subviews else {return} //此處就是使用背景View的好處作烟,保證遍歷的時候只遍歷需要遍歷的內(nèi)容
for btn in btns {
if btn != sender && btn is UIButton && (btn as! UIButton).isSelected { //主要作用是去除其他已點擊按鈕的狀態(tài)
(btn as! UIButton).isSelected = false
(btn as! UIButton).backgroundColor = UIColor.white
}
}
}
效果如下:
image.png
2愉粤、一些規(guī)則的選擇性控件可以使用UItableView和UICollectionView來實現(xiàn)。
如下以一個tableView的需求為例:
image.png
使用UItableView和UICollectionView實現(xiàn)的方式比較統(tǒng)一拿撩∫吕澹可以使用系統(tǒng)自帶的機制解決問題。
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if self.isSelected {
self.selectIm.isHidden = false
} else {
self.selectIm.isHidden = true
}
}
通過Cell的選中和非選中來標識我們的業(yè)務(wù)需求压恒。
另外初始化的默認選中方式為:
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
這樣就需求實現(xiàn)了影暴。我們獲取選擇的內(nèi)容只需要去點擊的代理方法拿就OK了。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectString = listArray[indexPath.row]
}