Как создать кнопку смахивания для запуска с помощью движущихся стрелок - PullRequest
0 голосов
/ 24 декабря 2018

Я хочу создать точно такую ​​же кнопку прокрутки, как эта https://github.com/shadowfaxtech/proSwipeButton.Мне было интересно, как изменить стрелку кнопки при касании пользователя

Я делал это для получения действия смахивания.

let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
rightSwipe.direction = .right
view.addGestureRecognizer(rightSwipe)

, но дело в том, как добавить стрелки к кнопке, которые меняюттам позиция по касанию пользователя.

Ответы [ 2 ]

0 голосов
/ 24 декабря 2018

Ммм, а как же так?Вы можете добавить UIImage в раскадровку в переменной swipeImage.Наилучший эффект достигается, если изображение имеет тот же цвет текста.

import UIKit

@IBDesignable
class UISwipeableLabel: UILabel {

    @IBInspectable var swipeImage: UIImage? {
        didSet {
            configureSwipeImage()
        }
    }

    private var swipeImageView: UIImageView?
    private var rightSwipe: UIPanGestureRecognizer?
    private var shouldActivateButton = true

    override func awakeFromNib() {
        super.awakeFromNib()
        configureSwipeImage()
         clipsToBounds = true
    }
}

private extension UISwipeableLabel {

    @objc func handleSwipes(_ sender:UIPanGestureRecognizer) {
        if let centerX = swipeImageView?.center.x {
            let translation = sender.translation(in: self)
            let percent = centerX/frame.width

             if sender.state == .changed {
                if centerX < frame.width - frame.height/2 {
                    swipeImageView?.center.x = centerX + translation.x
                    sender.setTranslation(CGPoint.zero, in: swipeImageView)
                } else {
                    swipeImageView?.center.x = frame.width - frame.height/2
                    if shouldActivateButton {
                        activateButton()
                    }
                }
            }

             if sender.state == .ended || sender.state == .cancelled || sender.state == .failed {
                if shouldActivateButton {
                    UIView.animate(withDuration: 0.25 * TimeInterval(percent)) {
                        self.swipeImageView?.center.x = self.frame.height/2
                    }
                }
            }
        }
    }

    func configureSwipeImage() {
        if swipeImageView != nil {
            swipeImageView?.removeFromSuperview()
        }

        swipeImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.height, height: frame.height))

        if let swipeImageView = swipeImageView {
            swipeImageView.image = swipeImage
            swipeImageView.isUserInteractionEnabled =  true
             swipeImageView.alpha = 0.5
             addSubview(swipeImageView)


             rightSwipe = UIPanGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
            if let rightSwipe = rightSwipe {
                swipeImageView.addGestureRecognizer(rightSwipe)
            }
        }
    }

    func activateButton() {
        print("*** DO YOUR STUFF HERE ***")
        }
}

Вы начинаете с UILabel и, если хотите, измените его на использование autolayout.

0 голосов
/ 24 декабря 2018

Вот код, который я написал для пролистывания кнопки.Вы назначаете изображение для просмотра изображения.

func createSwipeButton() {
        let button = UIButton.init(type: .custom)
        button.backgroundColor = UIColor.brown
        button.setTitle("PLACE ORDER", for: .normal)
        button.frame = CGRect.init(x: 10, y: 200, width: self.view.frame.size.width-20, height: 100)
        button.addTarget(self, action: #selector(swiped(_:event:)), for: .touchDragInside)
        button.addTarget(self, action: #selector(swipeEnded(_:event:)), for: .touchUpInside)
        self.view.addSubview(button)

        let swipableView = UIImageView.init()
        swipableView.frame = CGRect.init(x: 0, y: 0, width: 20, height: button.frame.size.height)
        swipableView.tag = 20
        swipableView.backgroundColor = UIColor.white
        button.addSubview(swipableView)
    }

    @objc func swiped(_ sender : UIButton, event: UIEvent) {
        let swipableView = sender.viewWithTag(20)!
        let centerPosition = location(event: event, subView: swipableView, superView: sender,isSwiping: true)
        UIView.animate(withDuration: 0.2) {
            swipableView.center = centerPosition
        }
    }

    @objc func swipeEnded(_ sender : UIButton, event: UIEvent) {
        let swipableView = sender.viewWithTag(20)!
        let centerPosition = location(event: event, subView: swipableView, superView: sender, isSwiping: false)
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .curveEaseInOut, animations: {
            swipableView.center = centerPosition
        }) { _ in}
    }

    func location(event: UIEvent, subView: UIView, superView: UIButton, isSwiping: Bool) -> CGPoint {
        if let touch = event.touches(for: superView)?.first{
            let previousLocation = touch.previousLocation(in: superView)
            let location = touch.location(in: superView)
            let delta_x = location.x - previousLocation.x;
            print(subView.center.x + delta_x)
            var centerPosition = CGPoint.init(x: subView.center.x + delta_x, y: subView.center.y)
            let minX = subView.frame.size.width/2
            let maxX = superView.frame.size.width - subView.frame.size.width/2
            centerPosition.x = centerPosition.x < minX ? minX : centerPosition.x
            centerPosition.x = centerPosition.x > maxX ? maxX : centerPosition.x
            if !isSwiping{
                let normalPosition = superView.frame.size.width * 0.5
                centerPosition.x = centerPosition.x > normalPosition ? maxX : minX
                centerPosition.x = centerPosition.x <= normalPosition ? minX : centerPosition.x
            }
            return centerPosition
        }
        return CGPoint.zero
    }

enter image description here

Полный проект находится на github: https://github.com/IamSaurav/SwipeButton

...