美文网首页
iOS圆形UIButton实现只点击圆形区域有效

iOS圆形UIButton实现只点击圆形区域有效

作者: SmallWhiteMouse | 来源:发表于2018-03-27 14:27 被阅读40次

 系统UIButton自带的方式为矩形,通过设置layer层可以将图片裁剪为圆形,但是点击区域仍是矩形。

即: btn.layer.cornerRadius = 150; //矩形边长的一半

    btn.layer.masksToBounds = NO;//设置超过子图层的部分裁减掉

为解决这个为题,本文的方法是,创建UIButton子类,重写UIButton的- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event的方法。代码如下:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{

    BOOL  flag = [super pointInside:point withEvent:event];

    if (flag) {

        UIBezierPath   *path = [UIBezierPath bezierPathWithOvalInRect:self.bounds];

        if ([path containsPoint:point]) {

            return YES;

        }

    }

    return NO;

}

相关文章

网友评论

      本文标题:iOS圆形UIButton实现只点击圆形区域有效

      本文链接:https://www.haomeiwen.com/subject/bxxscftx.html