至于把标题的UILabel作为兄弟鉴于布伦特的想法,它似乎并不像我一个非常好的主意。我一直在思考与UILabel的交互问题,因为它的触摸事件没有通过UIButton的观点。
另一方面,用UILabel作为UIButton的子视图,我知道触摸事件总是会传播到UILabel的超级视图,所以我很舒服。
我确实采取了这种方法,并没有注意到任何使用backgroundImage报告的问题。我将这段代码添加到了UIButton子类的-titleRectForContentRect:中,但是代码也可以放在UIButton超级视图的绘制例程中,在这种情况下,您应该用UIButton的变量替换所有对自己的引用。
#define TITLE_LABEL_TAG 1234
- (CGRect)titleRectForContentRect:(CGRect)rect
{
// define the desired title inset margins based on the whole rect and its padding
UIEdgeInsets padding = [self titleEdgeInsets];
CGRect titleRect = CGRectMake(rect.origin.x + padding.left,
rect.origin.x + padding.top,
rect.size.width - (padding.right + padding.left),
rect.size.height - (padding.bottom + padding].top));
// save the current title view appearance
NSString *title = [self currentTitle];
UIColor *titleColor = [self currentTitleColor];
UIColor *titleShadowColor = [self currentTitleShadowColor];
// we only want to add our custom label once; only 1st pass shall return nil
UILabel *titleLabel = (UILabel*)[self viewWithTag:TITLE_LABEL_TAG];
if (!titleLabel)
{
// no custom label found (1st pass), we will be creating & adding it as subview
titleLabel = [[UILabel alloc] initWithFrame:titleRect];
[titleLabel setTag:TITLE_LABEL_TAG];
// make it multi-line
[titleLabel setNumberOfLines:0];
[titleLabel setLineBreakMode:UILineBreakModeWordWrap];
// title appearance setup; be at will to modify
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setFont:[self font]];
[titleLabel setShadowOffset:CGSizeMake(0, 1)];
[titleLabel setTextAlignment:UITextAlignmentCenter];
[self addSubview:titleLabel];
[titleLabel release];
}
// finally, put our label in original title view's state
[titleLabel setText:title];
[titleLabel setTextColor:titleColor];
[titleLabel setShadowColor:titleShadowColor];
// and return empty rect so that the original title view is hidden
return CGRectZero;
}
我确实花时间写了更多关于这个here。在那里,我还指出了一个较短的解决方案,虽然它不太适合所有情况,并涉及一些私人视图黑客攻击。在那里,你可以下载一个可以使用的UIButton子类。
`button.titleLabel .numberOfLines = 0` – ma11hew28 2015-05-12 23:46:37
请注意这个非常非常老QA ,在现代的Xcode **非常简单,选择“属性文本”**,然后它是微不足道的,选择“字符包装”。 – Fattie 2016-12-07 15:05:56
也见[更新的答案](http://stackoverflow.com/a/7832414/199364)到一个类似的问题。 – ToolmakerSteve 2017-03-06 00:11:31