LoginSignup
50
47

More than 5 years have passed since last update.

世界の中心で、アクションを叫ぶ

Last updated at Posted at 2015-06-30

Target Actionとは

OSX/iOSの開発では必須のなのでみなさんご存知ですよね。ね?

iOS Developer Library Target-Action

nilターゲット

ターゲットとしてnilを与えると、アクションはレスポンダーチェーン経由で処理されるようになります。これを利用するとviewからview controllerに簡単にアクションを送信することができます。

もちろん、プログラムから直接nilターゲットにアクションを送ることもできます。

ObjectiveC
    [UIApplication.sharedApplication sendAction:@selector(action:)
                                             to:nil
                                           from:self
                                       forEvent:nil];
swift
        UIApplication.sharedApplication().sendAction("action:", to: nil, from: self, forEvent: nil)

アクションを叫ぶ!

UITableViewCell等にボタンを配置した場合でも、nilターゲットを使うと簡単にview controllerまでイベントを送ることができます。あとは、senderからindexPathを取得すれば綺麗に処理が書けると思います。

senderがUITableViewCellのsubviewなので、そのindexPathは簡単に取得できます。UICollectionViewCellでも同じテクニックが使用できます。下記の例はUITableViewのカテゴリとして実装しているので、selfはTableViewと思って読んでください。

objectivec
- (UITableViewCell *)ppTableViewCellForView:(UIView *)view {
    if (view == nil) {
        return nil;
    }
    if ([view isKindOfClass:[UITableViewCell class]]) {
        return (UITableViewCell *) view;
    }
    return [self ppTableViewCellForView:view.superview];
}

- (NSIndexPath *)ppIndexPathForView:(UIView *)view {
    return [self indexPathForCell:[self ppTableViewCellForView:view]];
}
swift
import UIKit

extension UITableView{
    func btk_tableViewCellForView(view:UIView?)
        -> UITableViewCell?
    {
        if(view == nil){
            return nil
        }
        if let cell = view as? UITableViewCell{
            return cell
        }
        return btk_tableViewCellForView(view!.superview)
    }

    func btk_indexPathForView(view:UIView?)
        -> NSIndexPath?
    {
        if let cell = btk_tableViewCellForView(view){
            return indexPathForCell(cell)
        }
        return nil
    }
}

誰かに届け、このアクション!

50
47
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
50
47