2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift]UITableViewCellのaccessoryViewでaccessoryButtonTappedForRowWithIndexPathが来ない件の対応

Last updated at Posted at 2018-01-17

UITableViewCellのaccessoryViewにはUISwitchなどを設定できますが、いくらUISwitch
をタッチしてもaccessoryButtonTappedForRowWithIndexPathが呼ばれない。これは仕様らしい。

で、色々調べて、これが一番シンプルそうだった。
UISwitchViewにaddTargetでactionを設定してから、cell.accessoryViewに設定する。

xxxxxViewController.swift
func tableView(_ table: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:UITableViewCell = table.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
    if cell.accessoryView == nil{
        let switchView = UISwitch(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        switchView.isOn = false
        switchView.tag = indexPath.row
        switchView.addTarget(self, action: #selector(switchTriggered), for: .valueChanged)
        cell.accessoryView = switchView
    }

タッチされた時に呼ばれる処理。
(ここではUISwitchのON/OFFを配列に格納)

xxxxxViewController.swift
    @objc func switchTriggered(sender: UISwitch){
        switchs[sender.tag] = sender.isOn
    }

[確認環境]
Swift:4.0.3
Xcode:9.2


以下、参考元(というか、ほぼそのまま。)
ios - UISwitch in accessory view of a tableviewcell, passing a parameter with the selector to have selector function see the indexpath.row? - Stack Overflow

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?