所以我的自定义按钮如下所示:
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
}
我已将该按钮添加到Storyboard中的UIView,并将其子类化为此UIButton子类。我在Storyboard中将背景设置为蓝色。
结果:
问题是我点击角落(白色空间,好像按钮仍然被识别为正方形),它仍然是可点击的。这是一个问题,因为我想在彼此旁边添加多个这样的形状,所以我不希望任何按钮相互阻挡。
答案 0 :(得分:2)
您可以覆盖自定义UIButton
中的pointInside
功能,以控制何时应将视图界限中的触摸视为点击。
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)
}
另见
答案 1 :(得分:1)
如何将UITapGestureRecognizer添加到按钮视图,获取tap的坐标并将坐标转换为父视图坐标,并比较它是否在扭曲的立方体中。
//sender being the UITapGestureRecognizer
let coordinate = containerView.convertPoint(sender.locationInView(ContainerView), toCoordinateFromView: containerView)