现在的位置: 首页 > 综合 > 正文

UIButton 使用不规则图片,以及 长按短按事件

2018年04月19日 ⁄ 综合 ⁄ 共 1247字 ⁄ 字号 评论关闭

不规则按钮的添加,我这里使用的第三方插件OBShapedbutton,感谢Ole Begemann。
长按和短按的思路是:短按直接使用UIButton 的addtarge 方法,长按使用长按手势

上代码

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
    longPress.minimumPressDuration = 1; //定义按的时间
    
    OBShapedButton *newButton = [[OBShapedButton alloc]initWithFrame:CGRectMake(200, 200.0, 100, 100)];
    newButton.tag = 200;
    
    [newButton setBackgroundImage:[UIImage imageNamed:@"button-normal"] forState:UIControlStateNormal];
    [newButton setBackgroundImage:[UIImage imageNamed:@"button-highlighted"] forState:UIControlStateHighlighted];
    
    [newButton addGestureRecognizer:longPress];
    [newButton addTarget:self action:@selector(btnShort:) forControlEvents:UIControlEventTouchUpInside];

// 这里需要注意的是 长按事件如果不做 longPress.state == UIGestureRecognizerStateBegan 这个判断,会导致began,end 分别调用一次,显然我们需要避免这种情况。

-(void)btnLong:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan) {
        UIButton *newBTN =(UIButton *) longPress.view;
        NSLog(@"长按按钮的tag值:%d",newBTN.tag);
    }
    
}

-(void)btnShort:(UIButton *)newBtn
{
    NSLog(@"短按按钮的tag值%d",newBtn.tag);
}

DEMO下载地址:https://github.com/chexsong/WorkingDemos  下的 ButtonLongPress


车小松http://blog.csdn.net/mangosnow

本文遵循“署名-非商业用途-保持一致”创作公用协议

抱歉!评论已关闭.