带有 customView 的 UIBarButtonItem 在 iOS4.1 中消失了

Posted

技术标签:

【中文标题】带有 customView 的 UIBarButtonItem 在 iOS4.1 中消失了【英文标题】:UIBarButtonItem with customView disappears in iOS4.1 【发布时间】:2011-03-29 00:58:50 【问题描述】:

我在我的应用程序中为 UIBarButtonItem 使用 customView。这在 ios4.2 中运行良好(并且没有关于 iOS4.0 的任何错误报告),但在 iOS4.1 中应用 customView 会使整个按钮消失。有谁知道为什么会发生这种情况/我做错了什么?这是我的代码:

//array with button particulars:
// - the UIBarButtonItem to apply
// - image for normal state
// - image for highlighted state
// - button title
// - method to handle the click/tap
NSArray *buttonArr = [NSArray arrayWithObjects:aUIBarButtonItem, @"btn_img.png", @"btn_img_over.png", @"btn_title", @"clickHandler:", nil];

//configure the UIButton to use as customView 
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.titleLabel.font = [UIFont boldSystemFontOfSize:10.0];
button.titleLabel.textColor = [UIColor whiteColor];
button.titleLabel.textAlignment = UITextAlignmentCenter;     
[button setTitle:[buttonArr objectAtIndex:3] forState:UIControlStateNormal];

// make the buttons content appear in the top-left
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];

CGSize textSize = [[button.titleLabel text] sizeWithFont:[button.titleLabel font]];
CGFloat labelWidth = textSize.width;

buttonImage = [UIImage imageNamed:[buttonArr objectAtIndex:1]];
[button setImage:buttonImage forState:UIControlStateNormal];

buttonImage = [UIImage imageNamed:[buttonArr objectAtIndex:2]];
[button setImage: buttonImage forState:UIControlStateHighlighted];
[button setImage: buttonImage forState:UIControlStateDisabled];

[button addTarget:self action:NSSelectorFromString([buttonArr objectAtIndex:4]) forControlEvents:UIControlEventTouchUpInside];

// move text 10 pixels down and right
[button setTitleEdgeInsets:UIEdgeInsetsMake(50.0, -40.0, 0.0, 0.0)];
[button setImageEdgeInsets:UIEdgeInsetsMake(5.0, (labelWidth - buttonImage.size.width)/2 , 0.0 ,0.0)];      

button.frame = CGRectMake(0.0, 0.0, MAX(labelWidth, buttonImage.size.width),  buttonImage.size.height + 20);

//apply customView to UIBarButtonItem
barButton = (UIBarButtonItem *)[buttonArr objectAtIndex:0];          
barButton.customView = button;

【问题讨论】:

【参考方案1】:

对此有两种可能的解决方案:

    使用 [[UIBarButtonItem alloc] initWithCustomView::(UIView *)customView 而不是将 customView 分配给现有的 UIBarButtonItem。 添加button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);这一行(我自己没有测试过)

【讨论】:

以上是关于带有 customView 的 UIBarButtonItem 在 iOS4.1 中消失了的主要内容,如果未能解决你的问题,请参考以下文章

带有customView的自动布局iOS 11工具栏UIBarButtonItem

带有 xml 的 CustomView 不显示在屏幕上

从其他窗口将新项目添加到列表框

显示来自 Xib 的自定义视图

使用核心图形创建带有轮廓的图像

在 awakeFromNib() 上 - 错误实例成员 'button' 不能用于类型 'CustomView'