まだどこにもないアプリを作る

アプリ開発でつまづいたところなどを中心に記事にして行きます。

swift static tableView で特定のセルをタップした時の反応を実装

tableview の静的セルをタップした時の動作を実装するには didSelectRow内でindexPath.rowとindexPath.sectionの値をつかってif分岐することで実現できました

f:id:yuzurifa:20181210050229p:plain

今回はこの画像の上から4つ目のセルをタップしたらアラートが出るまでを実装します。

f:id:yuzurifa:20181210050415p:plain

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if indexPath.section == 3{
        let title: String = "このアプリを使用するには写真へのアクセスが必要です"
        let message: String = ""
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let settingsAction = UIAlertAction(title: "設定", style: .default, handler: { (_) -> Void in
            guard let settingsURL = URL(string: UIApplicationOpenSettingsURLString ) else {
                return
            }
            UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
        })
        let closeAction: UIAlertAction = UIAlertAction(title: "Close", style: .cancel, handler: nil)
        alert.addAction(settingsAction)
        alert.addAction(closeAction)
        self.present(alert, animated: true, completion: nil)
    }
    }

今回はindexPath.sectionだけをif 分岐で使いましたが、画像の上から三番目のセルの「利用規約」を押したときにやりたい場合は

if indexPath.section == 2 && indexPath.row == 1

と分岐すれば良いでしょう

アラートの実装はこちらの記事を参考にさせていただきました⬇︎

superhahnah.com