[英]How can I add a mask to a button so that the hidden area is not tappable?
我目前正在嘗試創建一個具有六邊形形狀的按鈕,但該按鈕仍會對其形狀之外的點擊做出反應。
我通過覆蓋func draw(_ rect: CGRect)
成功創建了形狀(見下文),但不幸的是我無法弄清楚如何將可點擊區域限制為形狀。
我也嘗試將clipsToBound
設置為true
,但這也無濟於事。
override func draw(_ rect: CGRect) {
let radiusOuterCircle: CGFloat = self.frame.width / 2
let centerXY = self.frame.width / 2
let initialPoint = CGPoint(x: 0, y: centerXY)
let shapePath = UIBezierPath()
shapePath.move(to: initialPoint)
let secondPoint = CGPoint(x: radiusOuterCircle / 2, y: abs(tan(CGFloat.pi / 3) * (radiusOuterCircle / 2)) + centerXY)
let thirdPoint = CGPoint(x: radiusOuterCircle / 2 * 3, y: secondPoint.y)
let fourthPoint = CGPoint(x: radiusOuterCircle * 2, y: centerXY)
let fifthPoint = CGPoint(x: thirdPoint.x, y: centerXY - abs(tan(CGFloat.pi / 3) * (radiusOuterCircle / 2)))
let sixthPoint = CGPoint(x: centerXY / 2, y: fifthPoint.y)
shapePath.addLine(to: secondPoint)
shapePath.addLine(to: thirdPoint)
shapePath.addLine(to: fourthPoint)
shapePath.addLine(to: fifthPoint)
shapePath.addLine(to: sixthPoint)
shapePath.close()
UIColor(red: 247/255, green: 204/255, blue: 47/255, alpha: 1.0).set()
shapePath.fill()
}
非常感謝:)
https://stackoverflow.com/a/36877464/7615046
這實際上是我的問題的答案。
您可以在下面找到我更新的代碼(Swift 5.1),因為其他代碼不再是最新的:
override func awakeFromNib() {
addTarget(self, action: #selector(touchDown(button:event:)), for: .touchDown)
}
override func draw(_ rect: CGRect) {
let radiusOuterCircle: CGFloat = self.frame.width / 2
let centerXY = self.frame.width / 2
let initialPoint = CGPoint(x: 0, y: centerXY)
shapePath.move(to: initialPoint)
let secondPoint = CGPoint(x: radiusOuterCircle / 2, y: abs(tan(CGFloat.pi / 3) * (radiusOuterCircle / 2)) + centerXY)
let thirdPoint = CGPoint(x: radiusOuterCircle / 2 * 3, y: secondPoint.y)
let fourthPoint = CGPoint(x: radiusOuterCircle * 2, y: centerXY)
let fifthPoint = CGPoint(x: thirdPoint.x, y: centerXY - abs(tan(CGFloat.pi / 3) * (radiusOuterCircle / 2)))
let sixthPoint = CGPoint(x: centerXY / 2, y: fifthPoint.y)
shapePath.addLine(to: secondPoint)
shapePath.addLine(to: thirdPoint)
shapePath.addLine(to: fourthPoint)
shapePath.addLine(to: fifthPoint)
shapePath.addLine(to: sixthPoint)
shapePath.close()
UIColor(red: 247/255, green: 204/255, blue: 47/255, alpha: 1.0).set()
shapePath.fill()
}
@objc func touchDown(button: HexagonButton, event: UIEvent) {
if let touch = event.touches(for: button)?.first {
let location = touch.location(in: button)
if shapePath.contains(location) == false {
button.cancelTracking(with: nil)
}
}
}
所有這些代碼都屬於自定義按鈕 class。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.