Ios 我有自定义的旋转45度的UIButtons-我如何使它只在实际形状中的空间是可点击的?
因此,我的自定义按钮如下所示:Ios 我有自定义的旋转45度的UIButtons-我如何使它只在实际形状中的空间是可点击的?,ios,swift,cashapelayer,Ios,Swift,Cashapelayer,因此,我的自定义按钮如下所示: override func drawRect(rect: CGRect) { let mask = CAShapeLayer() mask.frame = self.layer.bounds let width = self.layer.frame.size.width let height = self.layer.frame.size.height let path = CGPathCreateMutable()
override func drawRect(rect: CGRect) {
let mask = CAShapeLayer()
mask.frame = self.layer.bounds
let width = self.layer.frame.size.width
let height = self.layer.frame.size.height
let path = CGPathCreateMutable()
CGPathMoveToPoint(path,nil,width/2, 0)
CGPathAddLineToPoint(path,nil,width, height/2)
CGPathAddLineToPoint(path,nil,width/2, height)
CGPathAddLineToPoint(path,nil, 0, height/2)
mask.path = path
self.layer.mask = mask
}
我已经将该按钮添加到情节提要中的UIView中,并将其子类化到这个UIButton子类中。我在故事板中将背景设置为蓝色
结果:
问题是,当我在拐角处(空白处,好像按钮仍然被识别为正方形)单击时,它仍然可以单击。这是一个问题,因为我想在彼此旁边添加多个这样的形状,所以我不想让任何按钮相互阻挡。
您可以覆盖自定义ui按钮中的功能,以控制何时应将视图边界中的触摸视为点击
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
let width = bounds.size.width
let height = bounds.size.height
// Make a UIBezierPath that contains your clickable area
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: width / 2, y: 0))
path.addLineToPoint(CGPoint(x: width, y: height / 2))
path.addLineToPoint(CGPoint(x: width / 2, y: height))
path.addLineToPoint(CGPoint(x: 0, y: height / 2))
path.closePath()
// Let a hit happen if the point touched is in the path
return path.containsPoint(point)
}
另见
如何将UITapGestureRecognitor添加到按钮视图中,获取点击的坐标,并将坐标转换为父视图坐标,然后比较其是否在扭曲立方体中
//sender being the UITapGestureRecognizer
let coordinate = containerView.convertPoint(sender.locationInView(ContainerView), toCoordinateFromView: containerView)
你不能。因为,您不是在旋转按钮框,而是在为按钮创建自定义图像。红色区域仍被视为按钮框。尝试旋转按钮,而不是编写自定义代码。