UIButton 使用方法心得总结

   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 = @"ohMy 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时,响应结果如下图所示:





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值