質問

(通常のボタンの使用を使用して可能ではないように思わとして)UIToolbarButtonは、いくつかの平凡な方法を使って、その標的にオブジェクトを渡す作ることが可能ということですか?

私は

のようなものを意味します
UIBarButtonItem *Button = [[UIBarButtonItem alloc] initWithImage:buttonImage
  style:UIBarButtonItemStylePlain target:self action:@selector(doSomething:) **withObject:usingThis**];

私は、オブジェクトとの完全なメソッドを起動する方法をトリガすることができます知っているが、私は、コードを最小化しようとしていた優雅さのために...私はそれが可能ではないですが、あなたたちがそこにいるよう疑いますあなたが知っている超越答え... ...

と来るかもしれないめちゃくちゃ良いです
役に立ちましたか?

解決

あなたはUIBarButtonItemクラスを拡張する必要があります。

ここでRCBarButtonItemクラスを作成する例です。私は容易にするためinitWithTitleを使用しました、私はあなたがそれを変えることができると確信している...

のUIBarButtonItemサブクラス

#import <UIKit/UIKit.h>

@interface RCBarButtonItem : UIBarButtonItem {
    id anObject;
}

@property (nonatomic, retain) id anObject;

- (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action withObject:(id)obj;

@end

@implementation RCBarButtonItem

@synthesize anObject;

-(void)dealloc {
    [anObject release];
    [super dealloc];
}

- (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action withObject:(id)obj {
    if (self = [super initWithTitle:title style:style target:target action:action]) {
        self.anObject = obj;
    }
    return self;
}

@end

そして、これはそのようにように実装することができます:

#import "RootViewController.h"
#import "RCBarButtonItem.h"

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    RCBarButtonItem *button = [[RCBarButtonItem alloc] initWithTitle:@"Hello"
                                                               style:UIBarButtonItemStylePlain 
                                                              target:self
                                                              action:@selector(doSomething:)
                                                          withObject:@"Bye"];
    self.navigationItem.rightBarButtonItem = button;

}

- (void)doSomething:(id)sender {
    NSLog(@"%@", [(RCBarButtonItem *)sender anObject]);
}

他のヒント

私はこのような状況でやったことは、たとえば、buttonArgumentsと呼ばれるNSDictionaryのプロパティを作成しています

self. buttonArguments = [[NSDictionary alloc] initWithObjectsAndKeys: usingThis, Button, ... , nil];

次に、あなたのdoSomething:方法では、senderパラメータに基づいてオブジェクトを検索します。

私はカテゴリを使って好みます:

  

UIBarButtonItem + BarButtonItem.h

@interface UIBarButtonItem (BarButtonItem)
@property (strong, nonatomic) NSDictionary *userInfo;
@end
  

UIBarButtonItem + BarButtonItem.m

static void *kUserInfo = &kUserInfo;

@implementation UIBarButtonItem (BarButtonItem)

- (NSDictionary *)userInfo {
    return objc_getAssociatedObject(self, kUserInfo);
}

- (void)setUserInfo:(NSDictionary *)userInfo {
    objc_setAssociatedObject(self, kUserInfo, userInfo, 
        OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top