UIButtonのカスタムクラスで、6角形のボタンを作ろうとしています。
ストーリーボードでボタンを置き、そのクラスを下記のカスタムクラスに設定してます。親ビューの(0,0)の位置にUIButtonを置くとうまく六角形が表示されるのですが、それ以外の位置にすると表示されなくなります。
親ビューの座標が取れていないことが問題だと思うのですが、UIButtonのカスタムクラスから親ビューの座標を取る方法を知りたいです。よろしくお願いします。
swift
1import UIKit 2 3class HexagonButton: UIButton { 4 5 override init(frame: CGRect) { 6 super.init(frame: frame) 7 } 8 9 required init?(coder aDecoder: NSCoder) { 10 super.init(coder: aDecoder) 11 drawHexagon() 12 } 13 14 private func drawHexagon() { 15 let path = createHexagonPath() 16 17 let mask = CAShapeLayer() 18 mask.path = path.cgPath 19 20 self.layer.masksToBounds = true 21 self.layer.mask = mask 22 23 let borderShape = CAShapeLayer() 24 borderShape.path = path.cgPath 25 borderShape.lineWidth = 4.0 26 borderShape.strokeColor = UIColor.red.cgColor 27 borderShape.fillColor = UIColor.black.cgColor 28 self.layer.insertSublayer(borderShape, at: 0) 29 } 30 31 private func createHexagonPath() -> UIBezierPath { 32 let path = UIBezierPath() 33 34 print((superview ?? UIView()) ) 35 36 let view : UIView! = (superview ?? UIView()) 37 //6角形 38 path.move (to: CGPoint(x:self.center.x, 39 y:self.center.y + (superview?.frame.size.height)!/2)) 40 path.addLine(to: CGPoint(x:self.center.x + (superview?.frame.size.width)!/2, 41 y:self.center.y + (superview?.frame.size.height)!/4)) 42 path.addLine(to: CGPoint(x:self.center.x + (superview?.frame.size.width)!/2, 43 y:self.center.y - (superview?.frame.size.height)!/4)) 44 path.addLine(to: CGPoint(x:self.center.x, 45 y:self.center.y - (superview?.frame.size.height)!/2)) 46 path.addLine(to: CGPoint(x:self.center.x - (superview?.frame.size.width)!/2, 47 y:self.center.y - (superview?.frame.size.height)!/4)) 48 path.addLine(to: CGPoint(x:self.center.x - (superview?.frame.size.width)!/2, 49 y:self.center.y + (superview?.frame.size.height)!/4)) 50 51 path.close() 52 return path 53 } 54 55} 56
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/02/25 10:19