创建:120630为UIButton加入背景图片很容易,但是如果背景图片是以重叠方式加入的,而非一个完整的图片,则比较困难。
思路是建立一个sublayer加入到button的layer上。该sublayer负责加入背景图片。
同时,layer的borderColor设定边框,sublayer的borderColor设定内部边框。
同时要注意:初始的button的宽高一定要很长,否则无法正确加载图片和边框。
同时,textLabel一定要重新调整到最前方,否则,无法在显示文字。
@implementation UIButton (ContextualAction)
- (void)setContextualActionStyle
{
UIButton *button = self;
CGRect oldFrame = button.frame;
button.frame = CGRectMake(0.0f, 0.0f, 1000.0f, 1000.0f); // width and height must be bigger enough.
CALayer *layer = button.layer;
layer.cornerRadius = 5.0f;
layer.masksToBounds = YES;
layer.borderWidth = 1.0f;
layer.borderColor = [UIColor lightGrayColor].CGColor;
CALayer *shineLayer = [CALayer layer];
shineLayer.frame = button.layer.bounds;
UIImage *lightGrayBackgroundImage = [UIImage imageNamed:@"texture_light.png"];
shineLayer.backgroundColor = [UIColor colorWithPatternImage:lightGrayBackgroundImage].CGColor;
shineLayer.borderWidth = 2.0f; // 1.0f px will be cover by layer.border.
shineLayer.borderColor = [UIColor whiteColor].CGColor;
[button.layer addSublayer:shineLayer];
button.titleLabel.textAlignment = UITextAlignmentCenter;
button.titleLabel.font = [UIFont boldSystemFontOfSize:10];
[button setTitleColor:[UIColor colorWithRed:102.0f/255.0f green:102.0f/255.0fblue:102.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
[button setTitleShadowColor:[UIColor whiteColor] forState:UIControlStateNormal];
button.titleLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
[button bringSubviewToFront:button.titleLabel]; // must add. otherwise the title won't show.
button.frame = oldFrame;
}
@end
+++++