iOS上的圆形按钮

时间:2012-03-26 12:04:15

标签: iphone objective-c ios button geometry

是否可以创建如下图所示的两个按钮?看起来你应该使用UIButton或UIImageView但是如果我点击区域1,它仍然可以点击按钮1.当我点击区域1时,按钮2应该被触发!

enter image description here

7 个答案:

答案 0 :(得分:7)

如果上述回复未被接受,您可以实现覆盖pointInside:withEvent:的自定义UIButton子类。

假设您的视图完全是正方形且图形完全是圆形并填充整个正方形,示例可能是:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    // check that the point is at least inside the normal rect
    if(![super pointInside:point withEvent:event]) return NO;

    // we'll assume a square view with an exact circle inside, so
    // the radius of the circle is just half the width
    CGFloat radius = self.bounds.size.width*0.5f;

    // the point (radius, radius) is also the centre of the view, so...
    CGFloat squareOfDistanceFromCentre =
          (radius - point.x)*(radius - point.x) +
          (radius - point.y)*(radius - point.y);

    // if the point is too far away, return NO
    if(squareOfDistanceFromCentre > radius*radius) return NO;

    // otherwise we've exhausted possible reasons for answering NO
    return YES;
}

答案 1 :(得分:3)

您可以通过剪切图层并设置按钮的半径来制作圆形按钮。

[[button layer] setCornerRadius:8.0f];

您也可以尝试更改半径。

答案 2 :(得分:0)

是的,当然是可能的。

您可以通过IB将单个操作与多个选择器连接起来。
您还可以从button1触发的方法内直接调用button2触发的方法。

答案 3 :(得分:0)

这很棘手,但有可能: 您只能使用一个按钮,但在事件touchUpInside之后进行一些验证。您应该计算此触摸点是否在“button1”的圆圈内。对于此任务,您需要具备一些数学知识 - How do I calculate a point on a circle’s circumference?

答案 4 :(得分:0)

将较小的Button 1的userInteractionEnabled设置为NO。所有事件都将转到较大的Button 2.

答案 5 :(得分:0)

我为此创建了两个圆形矩形按钮,其中一个是长而薄的,另一个是更宽的。他们一起构建了一个像胖乎乎的加号的形状,这非常接近圆形,考虑到苹果接受44像素作为最小的可压缩尺寸。如果您想要更改图像,请将另一个图像设置为其imageView以获得突出显示的状态,并连接多个操作(如果您想在图像视图上模仿按钮突出显示状态,则触摸不足)。或者,您可以根据按钮

添加观察者并更改图像视图的突出显示状态

答案 6 :(得分:0)

在圆形按钮上处理pointInside的一种干净方法是:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    if (![super pointInside:point withEvent:event])
    {
        return NO;
    }
    BOOL isInside = (pow((point.x-self.frame.size.width/2), 2) + pow((point.y - self.frame.size.height/2), 2) < pow((self.frame.size.width/2), 2)) ? YES:NO;
    return isInside;
}

你可以放弃'isInside'变量,但这种方式更容易测试。