按下时工具栏按钮不会被激活

时间:2015-01-15 15:33:28

标签: ios objective-c button toolbar

我以编程方式在工具栏中添加了一个按钮,但它不起作用。我的代码有什么问题?它甚至不能压下。就像它只是工具栏上的一张图片一样。

-(void)viewWillAppear:(BOOL)animated{

   //Toolbar send button
   UIView *buttonContainer1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
   buttonContainer1.backgroundColor = [UIColor clearColor];
   UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
   [button1 setBackgroundImage:[UIImage imageNamed:@"send.png"] forState:UIControlStateNormal];
   const CGSize button1Size = [button1 sizeThatFits:CGSizeZero];
   [button1 setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-40, 27, button1Size.width, button1Size.height)];
   [button1 addTarget:self action:@selector(button1Action:) forControlEvents:UIControlEventTouchUpInside];
   [button1 setShowsTouchWhenHighlighted:YES];
   [buttonContainer1 addSubview:button1];

}

-(IBAction)button1Action:(id)sender{
   textField.textColor = [UIColor lightGrayColor];
   textField.text = @"the message was sent";
   [textField resignFirstResponder];

}

2 个答案:

答案 0 :(得分:0)

将以下代码用于文本字段的工具栏。我一直在我的代码中使用它

 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button.layer setMasksToBounds:YES];
button.frame=CGRectMake(0.0, 100.0, 60.0, 30.0);
[button addTarget:self action:@selector(button1Action:)  forControlEvents:UIControlEventTouchUpInside];

UIToolbar* keyboardDoneButtonView = [[UIToolbar alloc] init];
keyboardDoneButtonView.backgroundColor = [UIColor blackColor];
[keyboardDoneButtonView sizeToFit];
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithCustomView:button];
[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];
textfield.inputAccessoryView = keyboardDoneButtonView;

答案 1 :(得分:0)

您在viewWillAppear的最后忘记了一行重要的代码:

[self.view addSubview:buttonContainer1];

仅供参考 - 此代码应位于viewDidLoad,而不是viewWillAppear。可能会多次调用viewWillAppear,因此您最终会添加多个按钮。

您的代码与工具栏无关。