自定义滑块的响应缓慢

时间:2018-12-02 05:54:12

标签: ios swift custom-controls uislider

我正在尝试创建一个使用UIButton作为拇指的自定义滑块。由于似乎无法找到一种方法来使用UIView作为滑块中的拇指,因此我决定构建一个自定义的方法。但是,当我运行它时,拇指对初始阻力反应迟钝。以下是到目前为止的代码。以下gif的运行速度低于实际速度,但说明了这一点。

import Foundation
import UIKit

class CustomSlider: UIView, UIGestureRecognizerDelegate {
    let buttonView = UIButton()
    var minimumPosition = CGPoint()
    var maximumPosition = CGPoint()
    var originalCenter = CGPoint()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        // add a pan recognizer
        let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:)))
        recognizer.delegate = self
        addGestureRecognizer(recognizer)

        backgroundColor = UIColor.green

        buttonView.frame = CGRect(x: 0, y: 0, width: bounds.height, height: bounds.height)
        buttonView.backgroundColor = UIColor.purple
        self.addSubview(buttonView)

        minimumPosition = CGPoint(x:buttonView.frame.width / 2, y: 0)
        maximumPosition = CGPoint(x: bounds.width - buttonView.frame.width / 2, y: 0)
    }

    @objc func handlePan(recognizer: UIPanGestureRecognizer) {
        if recognizer.state == .began {
            originalCenter = buttonView.center
        }
        if recognizer.state == .changed {
            let translation = recognizer.translation(in: self)
            let newX = originalCenter.x + translation.x
            buttonView.center = CGPoint(x: min(maximumPosition.x, max(minimumPosition.x, newX)), y: buttonView.frame.midY)
        }
    }
}

sluggish_thumb

2 个答案:

答案 0 :(得分:0)

要使它看起来更平滑,您应该重置平移平移,然后将其连续添加到中心偏移处:

@objc func handlePan(recognizer: UIPanGestureRecognizer) {
    if recognizer.state == .began {
        // originalCenter = buttonView.center
    }
    if recognizer.state == .changed {
        originalCenter = buttonView.center
        let translation = recognizer.translation(in: self)
        let newX = originalCenter.x + translation.x
        buttonView.center = CGPoint(x: min(maximumPosition.x, max(minimumPosition.x, newX)), y: buttonView.frame.midY)

        recognizer.setTranslation(.zero, in: self)
    }
}

此外,要制作自定义控件,您可以查看本教程: how_to_check_if_vertex_is_visible_for_user

它可能已经很老了并且在Objective-c中,但是它给出了重写UIControl,处理触摸并创建自定义控件的一般思想-您也可以使用@IBDesignable和@IBInspectable进行扩展。

希望有帮助。

答案 1 :(得分:0)

最后弄清楚了。它仅在iPhone XR模拟器中发生。尝试过iPhone XS等,它们像玻璃一样光滑。