咱只能分享些简单的代码了 - 设置按钮背景图片,按钮会根据图片大小自动进行适配。



#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface UIButton (UIButtonExt)

- (void)setBackgroundImage:(UIImage*)image;
- (void)setBackgroundImageByName:(NSString*)imageName;

@end


#import "UIButtonExt.h"


@implementation UIButton (UIButtonExt)

- (void)setBackgroundImage:(UIImage*)image
{
    CGRect rect;
    rect       = self.frame;    
    rect.size  = image.size;            // set button size as image size
    self.frame = rect;
    
    [self setBackgroundImage:image forState:UIControlStateNormal];    
}

- (void)setBackgroundImageByName:(NSString*)imageName
{
    [self setBackgroundImage:[UIImage imageNamed:imageName]];
}

@end

调用示例如下:



    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];    
    myButton.frame = CGRectMake(80, 50, 10, 10);

        // set button background image here!!!
    [myButton setBackgroundImageByName:@"Brand.gif"];                  
     
    [self.view addSubview:myButton];
    
    [myButton setTitle:@"" forState:UIControlStateHighlighted];
    // add targets and actions
    [myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];     
posted on 2011-11-22 15:06  kitea  阅读(114)  评论(0)    收藏  举报