mzgkworks

iOSを中心にプログラミング関係について書く

【Swift】UITableViewのタッチイベントを検知する方法

UITableViewController(Static Cells使用)で、テーブルのセル内に入力欄(UITextField)を設置し、入力欄以外をタップした際にキーボードを消したい。
しかし、ViewController側でタッチイベントを検知していない。

どうやらUITableViewはUIScrollView同様に、タッチイベントをViewControllerまでレスポンダーチェーンさせない。
なので、クラス拡張(SwiftでいうExtension。Objective-Cでいうカテゴリ)で対応させる。
こんな画面。

f:id:mzgkworks:20150702184033p:plain

環境

  • Xcode 6.3.2
  • Swift 1.2
  • UITableViewController
  • TableView - Content:Static Cells

Extensionの作成

  • File -> New -> Fileで、.swiftファイルを作成する
  • 名前は任意(UITableView+TouchEvent.swiftで作成)
  • 出来上がったファイルに以下を記述
import Foundation  // もともと記述されている
import UIKit  // 忘れずに追記!!

extension UITableView {
    public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        // touchesBeganを次のレスポンダーにつなげる
        self.nextResponder()?.touchesBegan(touches, withEvent: event)
    }
}

イベントを処理する側(ここではUITableViewController)

  • touchesBeganを追加し、実行したい処理を記述する
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        // キーボードを閉じる
        self.view.endEditing(true)
    }