在自定义视图中向UIButton添加操作

时间:2010-12-17 09:36:55

标签: objective-c view uibutton action programmatically-created

我有一个自定义视图,它有一个UIButton。我将此视图添加到我的navigationItem的rightbarButtonItem,没关系,但我必须向此按钮添加一个动作。

这是我的代码;

-(void)showMessage:(id)sender
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"next" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [alert show];
}

- (void)viewDidLoad {
    UpDownButtonView *buttonView = [[UpDownButtonView alloc] initWithNibName:@"UpDownButtonView" bundle:nil];
    [buttonView.upButton addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
    [buttonView.downButton addTarget:self action:@selector(prev:) forControlEvents:UIControlEventTouchUpInside];
    buttonView.view.frame = CGRectMake(0,0,95,34);
    UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:buttonView.view]; 

    self.navigationItem.rightBarButtonItem = item;
    [self setTitle:@"Details"];

    [super viewDidLoad];
}

感谢。

1 个答案:

答案 0 :(得分:1)

您不需要使用UIButton的自定义视图,您需要的是分配并初始化UIBarButtonItem并将其放在导航栏上

代码看起来像:

UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Back", @"Back Button") style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed:)];

self.navigationItem.leftBarButtonItem = backButton;
[backButton release];