Swift - 圆形按钮

Swift - Round Button

我想在 swift 中创建几个圆形按钮,碰撞检测和重力作用于它们。但是每当我这样做时,在碰撞期间它们就像一个正方形,(我尝试将图像添加到按钮或通过代码创建它但结果保持不变),所以任何人都可以提供帮助,因为我想创建圆形按钮每当他们碰撞或坠落时就像圆形。

如果有碰撞和重力,请改用SpriteKit。在那里创建任何形状,因为 SKNode 可以工作。

试试 OBShapedButton

这是第三方 class 可用于不同形状类型的按钮和使用此创建的按钮 class 充当您为按钮提供的图像形状。

https://github.com/ole/OBShapedButton

要在故事板或 xib 文件中使用它,只需将 Custom Class as OBShapedButton 提供给 UIButton

或以编程方式

obj_OBShapedButton = [OBShapedButton buttonWithType:UIButtonTypeCustom];
[obj_OBShapedButton setFrame:CGRectMake(10, 10, 160,161)];

[obj_OBShapedButton setImage:[UIImage imageNamed:@"button-normal.png"] forState:UIControlStateNormal];
[obj_OBShapedButton addTarget:self action:@selector(Buton_action) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:obj_OBShapedButton];

实际回答原问题:

自从 iOS 9 发布后,您现在可以将碰撞形状更改为圆形(或任何其他形状)。

在您的 UIButton 子类中,您可以添加:

- (UIDynamicItemCollisionBoundsType)collisionBoundsType
{
    return UIDynamicItemCollisionBoundsTypeEllipse;
}

这会将碰撞边界设置为圆形而不是默认矩形。