不推薦更改UIButton的內部層次結構,因爲它可能會在未來的iOS更新中破壞。另外,它可能會導致Apple拒絕您的應用程序。更好的解決方案是創建一個按鈕子類。這裏是如何做到這一點的例子:
@interface MyButton : UIButton
@end
@implementation MyButton
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
[self addObserver:self forKeyPath:@"highlighted" options:NSKeyValueObservingOptionNew context:NULL];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
if (self.highlighted == YES)
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
const CGFloat *topGradientColorComponents = CGColorGetComponents([UIColor whiteColor].CGColor);
const CGFloat *bottomGradientColorComponents = CGColorGetComponents([UIColor blackColor].CGColor);
CGFloat colors[] =
{
topGradientColorComponents[0], topGradientColorComponents[1], topGradientColorComponents[2], topGradientColorComponents[3],
bottomGradientColorComponents[0], bottomGradientColorComponents[1], bottomGradientColorComponents[2], bottomGradientColorComponents[3]
};
CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0]) * 4));
CGColorSpaceRelease(rgb);
CGContextDrawLinearGradient(ctx, gradient, CGPointMake(0, 0), CGPointMake(0, self.bounds.size.height), 0);
CGGradientRelease(gradient);
}
else
{
// Do custom drawing for normal state
}
}
- (void)dealloc
{
[self removeObserver:self forKeyPath:@"highlighted"];
[super dealloc];
}
@end
您可能需要稍作修改,以得到它做你想要什麼,但我想你的基本理念。
有這個問題的好答案:http://stackoverflow.com/questions/14523348 /如何改變uibutton的background-color-of-uibutton-while-highlight- – ThomasW 2016-02-03 02:44:45