【Swift】CollectionViewのカスタムセルをタップすることでUISwitchを切り替える
9568 ワード
どういうことか
こういうことがやりたい。
どうするのか
- xibを使ってUIを作るが、この際にUIButtonでセル全体を覆ってしまうのがコツ
- どちらのセルをタップしたのかの判定も入れる
- Delegateを使う
カスタムセル側
ToggleCollectionViewCell.swift
protocol ToggleCollectionViewCellDelegate {
func toggleSwitchAction(toggleSwitchCheck: Bool, type: String)
}
class ToggleCollectionViewCell: UICollectionViewCell, Reusable {
@IBOutlet weak var toggleSwitch: UISwitch!
var toggleSwitchCheck = false
// どっちのセルをタップしたのか判定するための変数
var contentType = ""
var delegate: ToggleCollectionViewCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
@IBAction func titleButtonAction(_ sender: Any) {
// スイッチの切替処理
if toggleSwitchCheck {
toggleSwitch.setOn(false, animated:true)
toggleSwitchCheck = false
} else {
toggleSwitch.setOn(true, animated:true)
toggleSwitchCheck = true
}
// スイッチの判定とセルの判定を渡してあげる
delegate?.toggleSwitchAction(toggleSwitchCheck: toggleSwitchCheck, type: contentType)
}
}
Controller側
Delegateメソッドはextensionに書きます(自由ですが)。
セルをタップすることでController内のメンバ変数が切り替わるので、それによってなんらかの処理をしてあげるといい感じです。
ViewController.swift
// メンバ変数
var areYaru = false
var koreYaru = false
// 中略
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = CollectionViewUtility.createCell(collectionView, identifier: ToggleCollectionViewCell.reusableIdentifier, indexPath) as! ToggleCollectionViewCell
switch (indexPath.section) {
case 0:
cell.titleButtonLabel.setTitle("あれをやる", for: .normal)
cell.delegate = self
cell.contentType = "are"
return cell
case 1:
cell.titleButtonLabel.setTitle("これをやる", for: .normal)
cell.delegate = self
cell.contentType = "kore"
return cell
default:
return UICollectionViewCell()
}
}
// 中略
extension ViewController: ToggleCollectionViewCellDelegate {
// Delegateメソッド
func toggleSwitchAction(toggleSwitchCheck: Bool, type: String) {
if type == "userId" {
areYaru = toggleSwitchCheck
} else if type == "biometrics" {
koreYaru = toggleSwitchCheck
} else {
print("error")
}
}
}
おわり(´・ω・`)
Author And Source
この問題について(【Swift】CollectionViewのカスタムセルをタップすることでUISwitchを切り替える), 我々は、より多くの情報をここで見つけました https://qiita.com/antk/items/ac0615acff5432737d8a著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .