iphone - 在UIToolbarButton动作上传递一个对象

时间:2010-03-09 18:08:32

标签: iphone cocoa-touch uikit ipad

是否可以通过使用一些开放的方法使UIToolbarButton将对象传递给其目标(因为使用常规按钮似乎不可能)?

我的意思是

UIBarButtonItem *Button = [[UIBarButtonItem alloc] initWithImage:buttonImage
  style:UIBarButtonItemStylePlain target:self action:@selector(doSomething:) **withObject:usingThis**];

我知道我可以触发一个方法来启动对象的完整方法,但为了优雅,我试图最小化代码......我怀疑这是不可能的,但是你们那里的人都有疯狂的你可能会得到一个超然的答案......谁知道......

3 个答案:

答案 0 :(得分:4)

您必须扩展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]);
}

答案 1 :(得分:1)

我在这种情况下所做的是创建一个名为buttonArguments的NSDictionary属性:

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

然后在doSomething:方法中,根据sender参数查找对象。

答案 2 :(得分:0)

我更喜欢使用类别:

  

的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