UIBarButton类中的struct objc错误

时间:2013-06-06 08:19:56

标签: iphone uibarbuttonitem

我想创建一个自定义图像的按钮,因此我创建了一个子类UIBarButtonItem。

    @implementation UIBar

+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image target:(id)target action:(SEL)action{

    UIImage *menuButtonImage = [UIImage imageNamed:@"Camera.jpg"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:menuButtonImage forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, menuButtonImage.size.width, menuButtonImage.size.height);
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button addTarget:self action:@selector(takePicture) forControlEvents:UIControlEventTouchUpInside];


  //  self->navigationItem.rightBarButtonItem = menuButton;

    [UIViewController release];
}

但是我遇到了错误:

 self.navigationItem.rightBarButtonItem = button;

struct objc_class

类型的不完整定义

此错误是否与我的课程未正确初始化有关?我是Objective-C的新手。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

在类别方法中,您不会返回任何UIBarButtonItem实例。尝试返回menuButton。

我不确定为什么你需要调用UIViewController的类方法。例如,该方法不是类方法。删除该行。

+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image target:(id)target action:(SEL)action{

    UIImage *menuButtonImage = [UIImage imageNamed:@"Camera.jpg"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:menuButtonImage forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, menuButtonImage.size.width, menuButtonImage.size.height);
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button addTarget:self action:@selector(takePicture) forControlEvents:UIControlEventTouchUpInside];
    return menuButton; 
}

答案 1 :(得分:0)

如果你想要自定义栏按钮,那么你可以在viewController的viewDidLoad方法中使用以下代码。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
[button addTarget:self action: @selector(takePicture)forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = customBarItem;

如果您想要继承UIBarButtonItem,那么您可以执行以下操作。

@implementation UIBar

+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image target:(id)target action:(SEL)action
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    return menuButton;
}

并在viewController viewDidLoad方法中执行以下操作

 UIBar *customBarItem = [UIBar barItemWithImage:buttonImage target:self action:@selector(takePicture)];
 self.navigationItem.leftBarButtonItem = customBarItem;

这两种方法都有效。