2015-01-15 81 views
0

我已经编程添加了一个按钮到我的工具栏,但它不起作用。我的代码有什么问题?它甚至不是可压缩的。它就像它只是一个工具栏上的图片。工具栏按钮在按下时不会激活

-(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]; 

} 
+0

我明白你的意思了。我应该将sizeThatFits:参数设置为? – ian 2015-01-15 15:45:26

+0

你能找到你的按钮的宽度和高度吗? – 2015-01-15 15:46:30

+0

这是资产目录中的可调整大小的图像,因此它根据所使用的设备进行更改 – ian 2015-01-15 15:48:12

回答

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; 
+0

虽然此代码可能会用作替代方法,但此答案实际上并没有按照要求回答问题。 – rmaddy 2015-01-15 17:28:53

0

你忘了一个代码重要主线在viewWillAppear尽头:

[self.view addSubview:buttonContainer1]; 

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

没有关于您的代码与工具栏有任何关系。