UIButton控件是IOS开发中常用的控件之一,其使用方法主要涉及形状、颜色、大小以及响应事件等几方面:
//初始化并加载
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 400, 100, 50)]; //初始化button的大小
[self.view addSubview:button];
//标题
// button.titleLabel.text = @"控件"; //错误写法,因为titleLabel是只读的。
[button setTitle:@"控件" forState:UIControlStateNormal]; //正确写法
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//背景颜色
button.backgroundColor = [UIColor lightGrayColor];
//背景图片
[button setBackgroundImage:[UIImage imageNamed:@"控件.png"] forState:UIControlStateNormal];
//填充图片
[button setImage:[UIImage imageNamed:@"控件.png"] forState:UIControlStateNormal];
//添加消息响应事件
//响应方法1;该方法为一般方法,比较常用
// [button addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
//响应方法2;该方法可以获得触摸事件的属性,如触摸位置
[button addTarget:self action:@selector(buttonClicked: event:) forControlEvents:UIControlEventTouchUpInside];
//下面是上述响应方法的具体实现
方法1:
-(void)buttonClicked
{
NSString *msg = @"oh,My God,我被点中了!";
UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"消息提醒"
message:msg
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"确定",nil];
[alerView show];
}
当点击button时,响应结果如下图所示:
方法2:
-(void)buttonClicked:sender event:event
{
NSSet *touches = [event allTouches]; // 返回该接器所有触碰对象;
UITouch *touch = [touches anyObject]; // 返回Touch对象组中的其中一个对象
CGPoint currenrPos = [touch locationInView:self.view];
NSString *msg = [NSString stringWithFormat:@"讨厌,你点击了我%.0f,%.0f的位置",currenrPos.x,currenrPos.y];
UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"消息提醒"
message:msg
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"确定",nil];
[alerView show];
}
当点击button时,响应结果如下图所示: