ios - UIToolbar 的自定义 UIBarButtonItem

标签 ios objective-c uibarbuttonitem class-method

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

选择器完成按钮.h

#import <UIKit/UIKit.h>

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

选择器完成按钮.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 之后的选择器 View 方法)

#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];
}

我是否正确使用类方法?

最佳答案

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

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

关于ios - UIToolbar 的自定义 UIBarButtonItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35218330/

相关文章:

objective-c - 如何从自定义操作进入删除确认状态 UITableViewCell?

ios - UIBarButtonItem 在 UIToolBar 和 UINavigationBar 中的显示方式不同

ios - UITableView:重命名编辑按钮 (UIBarButtonSystemItemEdit)

objective-c - 传递带有核心日期 + Magical Record 的 ManagedContext

ios - 在 Facebook 上发布状态

ios - 在 Swift 中使用关键字过滤数组数组

objective-c - 调试是唯一在 Objective C 程序中使用 iVars 有意义的情况吗?

ios - LeftBarButtonItem 位置不正确

iphone - iOS : detect UIWebView reaching the top or bottom

iOS 应用程序的 PHP is_uploaded_file 失败