我想定制一个包含图像和文本的uibarbuttonite,如下所示:

在此处输入图像描述

我try 将uibarbuttonite子类化并重写此方法:

- (UIView *)customView
{
    if (!self.storedView) {

        UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
        UIImageView *tempImageView = [[UIImageView alloc] initWithImage:self.image];
        tempImageView.frame = CGRectMake(0, 0, self.image.size.width, self.image.size.height);
        UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, 0, 100, 44)];
        tempLabel.text = @"text";
        [temp addSubview:tempImageView];
        [temp addSubview:tempLabel];
        self.storedView = temp;
    }
    return self.storedView;
}

我是这样使用的:

UIBarButtonItem *left = [[LeftItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(settingsPressed)];
left.title = @"Settings";
left.image = [UIImage imageNamed:@"settings.png"];
self.navigationItem.leftBarButtonItem = left;

但用这个我只能得到图像,而不是标签.我做错了什么?

推荐答案

UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[button addTarget:target action:@selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 53, 31)];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(3, 5, 50, 20)];
[label setFont:[UIFont fontWithName:@"Arial-BoldMT" size:13]];
[label setText:title];
label.textAlignment = UITextAlignmentCenter;
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor clearColor]];
[button addSubview:label];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButton;

Objective-c相关问答推荐

Clang:将 id 之类的类型转换警告提升为 class

如何判断 iPhone 现在在哪个位置(横向或纵向)?

iOS8:退出应用程序后不久出现蓝条正在使用您的位置

在哪里以及如何 __bridge

UITableView/UITableViewCell 点击事件响应?

如何将 UInt32 设置为最大值

从 NSString 创建 SHA1 哈希

从 Storyboard 实例化视图控制器与创建新实例

Objective-C (cocoa) 等价于python的endswith/beginswith

如何在 iPhone 中将 NSData 转换为字节数组?

未找到 Apple Mach-O 链接器警告目录

[NSNull null] 和 nil 有什么区别?

如果目录不存在,是否有更安全的方法来创建目录?

如何将小时数添加到 NSDate?

自定义导航栏样式 - iOS

Xcode 7 UI 测试:如何在代码中消除一系列系统alert

获取当前调度队列?

目标覆盖 FRAMEWORK_SEARCH_PATHS 构建设置

iPhone - dequeueReusableCellWithIdentifier 用法

将参数传递给由 NSTimer 调用的方法