繁体   English   中英

UIToolbar的自定义UIBarButtonItem

[英]Custom UIBarButtonItem for UIToolbar

在测试项目中,我计划具有多个选择器视图。 对于这些选择器视图,将有UIToolbars和自定义UIBarButtons。 我试图创建一个类方法,以便不必重复代码,但是似乎按钮没有显示出来。

选择器完成Button.h

#import <UIKit/UIKit.h>

@interface UIBarButtonItem (test)
+ (UIBarButtonItem*)barButtonItemWithTint:(UIColor*)color andTitle:(NSString*)itemTitle andTarget:(id)theTarget andSelector:(SEL)selector;
@end

Picker完成Button.m

#import "PickerDoneButton.h"

@implementation UIBarButtonItem (test)
+ (UIBarButtonItem*)barButtonItemWithTint:(UIColor*)color andTitle:(NSString*)itemTitle andTarget:(id)theTarget andSelector:(SEL)selector
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tintColor = color;
    button.backgroundColor = [UIColor yellowColor];
    [button addTarget:theTarget action:selector forControlEvents:UIControlEventValueChanged];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    return doneButton;
}
@end

并在我的View Controller.m上使用此类方法(我省略了viewDidLoad之后的选择器视图方法)

#import "ViewController.h"
#import "PickerDoneButton.h"

@interface ViewController ()
@property (strong, nonatomic) NSArray *numberofPeople;
@property (strong, nonatomic) UIPickerView *countPeople;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.countPeople = [[UIPickerView alloc] init];
    self.countPeople.dataSource = self;
    self.countPeople.delegate = self;
    self.numberofPeople = @[@"1",@"2",@"3"];

    UIToolbar *countPeopleToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,0,50)];
    countPeopleToolbar.barStyle = UIBarStyleBlackOpaque;
    // Call the UIBarButtonItem from PickerDoneButton.h
    countPeopleToolbar.items = @[[UIBarButtonItem barButtonItemWithTint:[UIColor redColor] andTitle:@"Done" andTarget:self andSelector:@selector(doneClicked)]];
    [self pickerView:self.countPeople didSelectRow:0 inComponent:0];
}

我是否正确使用class方法?

是的,您做得正确。 唯一缺少的是您没有将button框架设置在doneButton 由于按钮没有设置任何框架,因此不会显示。 创建按钮后添加此按钮。

button.frame = CGRectMake(0, 0, 30, 30); // change frame as per your requirement

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM