1、动态创建
//创建按钮
UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//设置按钮位置
[sampleButton setFrame:CGRectMake(10, 100, self.view.bounds.size.width- 20, 52)];
//定义按钮标题
[sampleButton setTitle:@"Button Title" forState:UIControlStateNormal];
//定义按钮标题字体格式
[sampleButton.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
//定义按钮背景图片,redButton.png已经存在,拖放添加图片文件到image项目文件夹中
[sampleButton setBackgroundImage:[[UIImage imageNamed:@"redButton.png"]stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0] forState:UIControlStateNormal];
//添加点击按钮所执行的程式
[sampleButton addTarget:self action:@selector(buttonClicked)forControlEvents:UIControlEventTouchUpInside];
//在 View 中加入按钮
[self.viewaddSubview:sampleButton];
2、在xib文件中已经创建好,通过tag获取按钮
UIButton *testButton= (UIButton*)[self.view viewWithTag:100];
[testButton addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];
//按钮事件
-(void) test: (id) sender{
UIAlertView *av = [[[UIAlertView alloc] initWithTitle:@"ceshi" message:@"test11111" delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil] autorelease];
[av show];
}
3.设置按钮图片
adjustsImageWhenHighlighted property // 确定当按钮高亮时图片是否改变的BOOL值,为真时图片随按钮高亮而高亮
adjustsImageWhenDisabled property // 确定当按钮高亮时图片是否改变的BOOL值,为真时图片随按钮失效而变暗
showsTouchWhenHighlighted property // 控制当按钮按下时是否闪光的BOOL值.默认NO,YES时按下会有白色光点.图片和按钮事件的不会因闪光改变.
– backgroundImageForState: // 返回某个按钮状态下使用的背景图片.
– imageForState: // 返回某个状态下的按钮图片.
– setBackgroundImage:forState: // 设置特定状态的背景图片,默认都是normal
– setImage:forState: // 设置特定状态的图片,默认都是norm
4、其他
按钮种类
typedef enum {
UIButtonTypeCustom = 0, // 没有风格
UIButtonTypeRoundedRect, // 圆角风格按钮
UIButtonTypeDetailDisclosure, //
UIButtonTypeInfoLight, // 明亮背景的信息按钮
UIButtonTypeInfoDark, // 黑暗背景的信息按钮
UIButtonTypeContactAdd, //
} UIButtonType;
按钮状态:
UIControlEventTouchDown // 按下
UIControlEventTouchDownRepeat // 多次按下
UIControlEventTouchDragInside // 保持按下然后在按钮及其一定的外围拖动
UIControlEventTouchDragOutside // 保持按下,在按钮外面拖动
UIControlEventTouchDragEnter // DragOutside进入DragInside触发
UIControlEventTouchDragExit // in到out触发
UIControlEventTouchUpInside // 在按钮及其一定外围内松开
UIControlEventTouchUpOutside // 按钮外面松开
UIControlEventTouchCancel // 点击取消
UIButton *Button_Login = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //边框设置
Button_Login.frame = CGRectMake(143, 50, 40, 30); //位置及大小
Button_Login.backgroundColor = [UIColor clearColor];
[Button_Login setTitle:@"Login" forState:UIControlStateNormal]; //按钮的提示字
Button_Login.titleLabel.font = [UIFont fontWithName:@"helvetica" size:12]; //设置字体大小
[Button_Login setBackgroundImage:[UIImage imageNamed:@"28.png"] forState:UIControlStateNormal]; //设置背景图片
[self.view addSubview:Button_Login];
[Button_Login addTarget:self action:@selector(Login_Judge) forControlEvents:UIControlEventTouchDown]; //触发到函数Login_Judge中
5、何时释放release UIButton?
是否在dealloc中对UIButton对象进行release操作,取决于UIButton初始化的方式。
如果使用[UIButtonbuttonWithType:UIButtonTypeRoundedRect]这种方式,是不需要进行release操作的,因为这种方式是自动释放的。如果使用 [[UIButton alloc]init]的方式,则需要主动进行release释放操作。