自定义UISlider不会结束

时间:2017-10-27 16:53:07

标签: ios swift animation uislider

我创建了一个UISlider,当值改变时,每个tick都有刻度线和快照。问题是滑块不会自然地到达末端,并且左侧和右侧的刻度在圆圈外部可见。我已经扩展了UISlider类以到达目的但是动画与将滑块移动到下一个刻度相冲突,并且圆圈最终离开屏幕。如何保持快照以勾选动画并让滑块中的圆圈一直到最后?这是我的代码

class CustomSlider: UISlider {

    override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect
    {
        let unadjustedThumbrect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
        let thumbOffsetToApplyOnEachSide:CGFloat = unadjustedThumbrect.size.width / 2.0
        let minOffsetToAdd = -thumbOffsetToApplyOnEachSide
        let maxOffsetToAdd = thumbOffsetToApplyOnEachSide
        let offsetForValue = minOffsetToAdd + (maxOffsetToAdd - minOffsetToAdd) * CGFloat(value / (self.maximumValue - self.minimumValue))
        var origin = unadjustedThumbrect.origin
        origin.x += offsetForValue
        return CGRect(origin: origin, size: unadjustedThumbrect.size)
    }
}

@IBOutlet weak var slider: CustomSlider!

let tickArray : [Float] = [Float(18),Float(20),Float(22),Float(24),Float(26),Float(28),Float(30)]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.slider.value = tickArray[0]
        self.slider.minimumValue = tickArray[0]
        self.slider.maximumValue = tickArray[6]
        self.slider.isContinuous = false



        var tick : UIView
        for i in 0..<tickArray.count-1 {
            tick = UIView(frame: CGRect(x: (self.slider.frame.size.width/6) * CGFloat(i), y: (slider.frame.size.height - 13) / 2, width: 2, height: 13))
            tick.backgroundColor = "8E8E93".hexColor
            slider.insertSubview(tick, belowSubview: slider)
        }

        tick = UIView(frame: CGRect(x: self.slider.frame.size.width-2, y: (slider.frame.size.height - 13) / 2, width: 2, height: 13))
        tick.backgroundColor = "8E8E93".hexColor
        slider.insertSubview(tick, belowSubview: slider)

    }

    @IBAction func sliderValueChanged(_ sender: UISlider) {


            if sender.value > tickArray[5] {
                slider.value = tickArray[6]
            } else if sender.value > tickArray[4] {
                slider.value = tickArray[5]
            } else if sender.value > tickArray[3] {
                slider.value = tickArray[4]
            } else if sender.value > tickArray[2] {
                slider.value = tickArray[3]
            } else if sender.value > tickArray[1] {
                slider.value = tickArray[2]
            } else if sender.value >
                tickArray[0] {
                slider.value = tickArray[1]
            } else {
                slider.value = tickArray[0]
            }
    }

enter image description here

1 个答案:

答案 0 :(得分:1)

当滑块移到边缘时,我通过隐藏左右刻度来解决我的问题。这消除了对滑块扩展的需要。