Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active May 29, 2016 04:32
Show Gist options
  • Save KentarouKanno/a9861ab12639499bfe8f1f388987368f to your computer and use it in GitHub Desktop.
Save KentarouKanno/a9861ab12639499bfe8f1f388987368f to your computer and use it in GitHub Desktop.
UIButton

UIButton Drag & Tap

★ ボタンタップ & ボタンドラッグができるCustom Button

import UIKit

class ViewController: UIViewController {
    
    let button1 = CustomButton(type: .Custom)
    let button2 = CustomButton(type: .Custom)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // ボタン1を生成
        button1.frame = CGRectMake(100, 100, 200, 50)
        button1.setTitle("Button1", forState: .Normal)
        button1.setTitleColor(UIColor.blueColor(), forState: .Normal)
        button1.backgroundColor = UIColor.yellowColor()
        button1.addTarget(self, action: #selector(ViewController.buttonPressed(_:)), forControlEvents: .TouchUpInside)
        button1.userInteractionEnabled = true
        button1.tag = 1
        view.addSubview(button1)
        
        // ボタン2を生成
        button2.frame = CGRectMake(100, 200, 200, 50)
        button2.setTitle("Button2", forState: .Normal)
        button2.setTitleColor(UIColor.blueColor(), forState: .Normal)
        button2.backgroundColor = UIColor.greenColor()
        button2.addTarget(self, action: #selector(ViewController.buttonPressed(_:)), forControlEvents: .TouchUpInside)
        button2.userInteractionEnabled = true
        button2.tag = 2
        view.addSubview(button2)
    }
    
    func buttonPressed(sender: UIButton) {
        if !button1.isMoveing && sender.tag == 1 {
            // ボタン1押下時のイベント
            print("Push! Button1")
        }
        
        if !button2.isMoveing && sender.tag == 2 {
            // ボタン2押下時のイベント
            print("Push! Button2")
        }
    }
}


// CustomButton Class
class CustomButton: UIButton {
    
    var isMoveing: Bool = false
    var position: CGPoint!
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        position = self.frame.origin
    }
    
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesMoved(touches, withEvent: event)
        
        isMoveing = true
        
        let touchEvent = touches.first!
        
        // ドラッグ前の座標
        let preDx = touchEvent.previousLocationInView(superview).x
        let preDy = touchEvent.previousLocationInView(superview).y
        
        // ドラッグ後の座標
        let newDx = touchEvent.locationInView(superview).x
        let newDy = touchEvent.locationInView(superview).y
        
        // ドラッグしたx座標の移動距離
        let dx = newDx - preDx
        
        // ドラッグしたy座標の移動距離
        let dy = newDy - preDy
        
        // 画像のフレーム
        var viewFrame: CGRect = self.frame
        
        // 移動分を反映させる
        viewFrame.origin.x += dx
        viewFrame.origin.y += dy
        self.frame = viewFrame
    }
    
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesEnded(touches, withEvent: event)
        isMoveing = false
        if position == self.frame.origin {
            self.sendActionsForControlEvents(.TouchUpInside)
        }
    }
}

★ GestureRecognizerを使用した場合(Code & xib両方OK)

// Usage

let button = CustomButton()

override func viewDidLoad() {
    super.viewDidLoad()

    // ボタンを生成
    button.frame = CGRectMake(100, 100, 200, 50)
    button.setTitle("Button", forState: .Normal)
    button.setTitleColor(UIColor.blueColor(), forState: .Normal)
    button.backgroundColor = UIColor.yellowColor()
    button.addTarget(self, action: #selector(ViewController.buttonPressed(_:)), forControlEvents: .TouchUpInside)
    button.userInteractionEnabled = true
    view.addSubview(button)
    
}

func buttonPressed(sender: UIButton) {
    print("Push! Button1")
}


// CustomButton Class
class CustomButton: UIButton {
    
    var gesture: UIGestureRecognizer!
    var startPoint:CGPoint!
    var endPoint:CGPoint!
    
    override init(frame: CGRect) {
        super.init(frame: CGRectZero)
        addGesture()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addGesture()
    }
    
    func addGesture() {
        guard let _ = gesture else {
            gesture = UIPanGestureRecognizer()
            gesture.addTarget(self, action: #selector(CustomButton.gestureAction(_:)))
            self.addGestureRecognizer(gesture)
            return
        }
    }
    
    func gestureAction(sender: UIPanGestureRecognizer) {
        
        let state = sender.state
        let translation = sender.translationInView(superview)
        // print("state = \(state.rawValue) translation = \(translation)")
        
        switch state {
        case .Began:
            startPoint = sender.view!.center
            print("Start Center Point = ",startPoint)
        case .Ended:
            endPoint = sender.view!.center
            print("End Center Point = ",endPoint)
        default:
            sender.view!.center.x = startPoint.x + translation.x
            sender.view!.center.y = startPoint.y + translation.y
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment