LoginSignup
0
0

More than 5 years have passed since last update.

お遊び:UIViewのsubviewsから、特定のプロトコルを持つUIViewを探してくる

Last updated at Posted at 2014-01-29

最初、【IOS備忘録】UISearchBarのテキストが空の状態で検索ボタンを有効にするをやりたかったのです。ですがiOS7時代だと、TextFieldがsubviewsの下の下の方に潜り込んでいるようで、このままでは動きません。
探してピンポイントで拾ってきても良いのですが、subviewsの中を再帰的に探してくる方が、楽しいじゃないですか。わくわくするじゃないですか。

というわけで、Underscore.mを使って、特定のプロトコルを実装したsubviewsを探してくるものを作りました。

@interface UIView(Util)
-(NSArray *)viewsFromSubviewsByMatchProtocol:(Protocol *)protocol;
@end

@implementation UIView(Util)
-(NSArray *)viewsFromSubviewsByMatchProtocol:(Protocol *)protocol
{
    // 1. 配列subviewsの中身を1つずつUIViewとして取り出す
    // 2-a. それがプロトコルを実装していればそれの入った配列を用意
    // 2-b. それがプロトコルを実装していなければ空の配列を用意
    // 3. 2.の配列とくっつけながら、再帰呼び出しして結果を配列で返す
    // 4. flattenで配列を整える
    return _.array(self.subviews).map(^NSArray *(UIView *view){
        NSArray *conformedViews =[view conformsToProtocol:protocol] ? @[view] : @[];
        return @[ conformedViews, [view viewsFromSubviewsByMatchProtocol:protocol]];
    }).flatten.unwrap;
}

@end

// 使うときはこんな感じ
NSArray *textFields = [UIView viewsFromSubviewsByMatchProtocol:@protocol(UITextInputTraits)];
id<UITextInputTraits> textField = textFields[0];


実用的か?といわれたら、さぁどうでしょう。
こんな書き方も出来るよ的なお遊びでした。

0
0
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
0
0