LoginSignup
13
14

More than 5 years have passed since last update.

UIViewに配置された特定のUI部品を検索する

Posted at

UIViewはsubviews、または入れ子として多数のUIViewを内包することがある。
タイトルに従い、特定のUI部品のインスタンスを検索してみる。

サンプルプロジェクトをつくる

Tabbed Applicationで自動生成されるFirst Viewをサンプルとしよう。
以下、プロジェクトの生成手順。

  1. メニュー > File > New > Projectで「Tabbed Application」を選択しNext
  2. 言語がswiftになっているか確認する。ProductNameを適当に入力し、Next。
  3. Createでプロジェクトが作成される
  4. FirstViewController.swiftを開く

複雑なUI部品を追加してやると面白いかもしれない。

コード

FirstViewControler.swift

import UIKit

class FirstViewController: UIViewController {

    var array:[AnyObject]!

    override func viewDidLoad() {
        super.viewDidLoad()        
        array = []

        // FirstView内のUILabelを検索する
        retrieveUIView(UILabel.self, parentView: self.view)

        println("UILabelの数: \(array.count)")
    }

    // parentViewのsubviews以下を検索
    // aClassのインスタンスがあればarrayへ追加
    func retrieveUIView(aClass: AnyClass, parentView: UIView) {
        for childView in parentView.subviews {

            // childViewのクラス名を出力
            // println("クラス: \(childView.dynamicType.description())")

            // childViewがaClassのインスタンスならばarrayに追加
            if (childView as NSObject).dynamicType.isEqual(aClass) {
                array.append(childView)
            }

            // 子のビューについて再帰
            retrieveUIView(aClass, parentView: childView as UIView)
        }
    }
}

ポイント

  • クラス名.selfでClass型に
  • .dynamicTypeに続けてドットでそのクラスのクラスメソッドにアクセス出来る
  • .selfと.dynamicTypeは補完候補に表示されない(xcode6 beta6)
  • UIPickerViewのように複雑なUI部品を構成する要素の1つ1つまで検索出来てしまう
13
14
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
13
14