2016-04-26 13 views

答えて

3

ここでは、特定の領域内のタッチにのみ反応するボタンの例を示します。

enter image description here

class MyButton: UIButton { 

    var path: UIBezierPath! 

    override func awakeFromNib() { 
     backgroundColor = UIColor.greenColor() 
     addTarget(self, action: #selector(touchDown), forControlEvents: .TouchDown) 
    } 
    override func drawRect(rect: CGRect) { 
     path = UIBezierPath() 

     path.moveToPoint(CGPointMake(150, 10)) 
     path.addLineToPoint(CGPointMake(200, 10)) 
     path.addLineToPoint(CGPointMake(150, 100)) 
     path.addLineToPoint(CGPointMake(100, 100)) 
     path.closePath() 

     let shapeLayer = CAShapeLayer() 
     shapeLayer.strokeColor = UIColor.redColor().CGColor 
     shapeLayer.fillColor = UIColor.blueColor().CGColor 
     shapeLayer.path = path.CGPath 
     layer.addSublayer(shapeLayer) 

    } 

    func touchDown(button: MyButton, event: UIEvent) { 
     if let touch = event.touchesForView(button)?.first { 
      let location = touch.locationInView(button) 

      if path.containsPoint(location) == false { 
       button.cancelTrackingWithEvent(nil) 
      } 
     } 

    } 
} 
0

あなたはスウィフト3/4でそれをしたい場合:

class MyButton: UIButton { 

    var path: UIBezierPath! 

    override func awakeFromNib() { 
     backgroundColor = UIColor.green 
     addTarget(self, action: #selector(touchDown), for: .touchDown) 
    } 
    override func draw(_ rect: CGRect) { 
     path = UIBezierPath() 

     path.move(to: CGPoint(x: 150, y: 10)) 
     path.addLine(to: CGPoint(x: 200, y: 10)) 
     path.addLine(to: CGPoint(x: 150, y: 100)) 
     path.addLine(to: CGPoint(x: 100, y: 100)) 
     path.close() 

     let shapeLayer = CAShapeLayer() 
     shapeLayer.strokeColor = UIColor.red.cgColor 
     shapeLayer.fillColor = UIColor.blue.cgColor 
     shapeLayer.path = path.cgPath 
     layer.addSublayer(shapeLayer) 

    } 

    func touchDown(button: MyButton, event: UIEvent) { 
     if let touch = event.touches(for: button)?.first { 
      let location = touch.location(in: button) 

      if path.contains(location) == false { 
       button.cancelTracking(with: nil) 
      } 
     } 
    } 
} 
関連する問題