转载自: http://code4app.com/snippets/one/%E7%BB%99UIButton%E6%B7%BB%E5%8A%A0-%E7%B1%BB%E5%88%AB-%E6%96%B9%E6%B3%95-%E6%96%B9%E4%BE%BF%E6%89%B9%E9%87%8F%E5%88%9B%E5%BB%BAbutton/51f0e2d36803fab305000006#s0
.h
//
// UIButton+Create.h
//
// Created by 魏建科 on 13-7-25.
// Copyright (c) 2013年 魏建科. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface
UIButton
(Create)
+ (UIButton*)
createButtonWithFrame
: (CGRect) frame
Target
:(
id
)target
Selector
:(
SEL
)selector
Image
:(
NSString
*)image
ImagePressed
:(
NSString
*)imagePressed;
+ (
UIButton
*)
createButtonWithFrame
:(CGRect)frame
Title
:(
NSString
*)title
Target
:(
id
)target
Selector
:(
SEL
)selector;
@end
.m
//
// UIButton+Create.m
//
// Created by 魏建科 on 13-7-25.
// Copyright (c) 2013年 魏建科. All rights reserved.
//
#import "UIButton+Create.h"
@implementation
UIButton
(Create)
+ (UIButton*)
createButtonWithFrame
: (CGRect) frame
Target
:(
id
)target
Selector
:(
SEL
)selector
Image
:(
NSString
*)image
ImagePressed
:(
NSString
*)imagePressed
{
UIButton
* button = [
UIButton
buttonWithType
:UIButtonTypeCustom];
[button
setFrame
:frame];
UIImage
*newImage = [
UIImage
imageNamed
:
image
];
[button
setBackgroundImage
:newImage
forState
:UIControlStateNormal];
UIImage
*newPressedImage = [
UIImage
imageNamed
:
imagePressed
];
[button
setBackgroundImage
:newPressedImage
forState
:UIControlStateHighlighted];
[button
addTarget
:target
action
:selector
forControlEvents
:UIControlEventTouchUpInside];
return
button;
}
+ (
UIButton
*)
createButtonWithFrame
:(CGRect)frame
Title
:(
NSString
*)title
Target
:(
id
)target
Selector
:(
SEL
)selector
{
UIButton
* button = [
UIButton
buttonWithType
:UIButtonTypeRoundedRect];
[button
setFrame
:frame];
[button
setTitle
:title
forState
:UIControlStateNormal];
[button
addTarget
:target
action
:selector
forControlEvents
:UIControlEventTouchUpInside];
return
button;
}
@end
使用方法,首先在要使用的ViewController
包含#import "UIButton+Create
.h
"
然后使用方法
- (
void
)viewDidLoad
{
[
super
viewDidLoad
];
[
self
.view
addSubview
:[
UIButton
createButtonWithFrame
:CGRectMake(
0
,
0
,
1
6
0
,
4
0
)
Title
:
@"测试"
Target
:
self
Selector
:
@selector
(buttonPressed:)]];
[
self
.view
addSubview
:[
UIButton
createButtonWithFrame
:CGRectMake(
0
,
1
0
0
,
1
6
0
,
4
0
)
Target
:
self
Selector
:
@selector
(buttonPressed:)
Image
:
@"这个是你给这个Button设置的默认图片"
ImagePressed
:
@"button点击后显示的高亮的图片"
]];
}
- (
void
)buttonPressed:(
id
)sender
{
}