1

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

我的意思是

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

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

4

3 回答 3

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]);
}
于 2010-03-09T18:43:26.920 回答
1

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

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

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

于 2010-03-09T18:17:05.893 回答
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
于 2014-10-10T15:28:26.463 回答