自定义UISlider可视化错误(拇指位置,轨道边缘......)

时间:2017-11-07 14:07:35

标签: ios swift uislider

这是我第一次在这里提问,如果我的问题中有任何不清楚的地方,请告诉我,谢谢。

所以我是iOS的新手,最近我为一个项目创建了一个自定义滑块,看起来像iOS风格的开关。以下是我的代码:

    @IBDesignable
    class CustomSlider: UISlider {

        @IBInspectable var trackWidth: CGFloat = 70
        @IBInspectable var trackHeight: CGFloat = 30
        @IBInspectable var thumbHeight: CGFloat = 30
        private var thumbTouchSize = CGSize(width: 70, height: 30)


        override func trackRect(forBounds bounds: CGRect) -> CGRect {
            return CGRect(origin: bounds.origin, size: CGSize(width: bounds.width, height: trackHeight))
        }


        override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {

            var thumb = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)

            thumb.size.height = thumbHeight
            return thumb.offsetBy(dx: 0, dy: 0)
        }


        override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
            let increasedBounds = bounds.insetBy(dx: -thumbTouchSize.width, dy: -thumbTouchSize.height)

            let containsPoint = increasedBounds.contains(point)
            return containsPoint
        }


        override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
            let percentage = CGFloat((value - minimumValue) / (maximumValue - minimumValue))
            let thumbSizeHeight = thumbRect(forBounds: bounds, trackRect:trackRect(forBounds: bounds), value:0).size.height
            let thumbPosition = thumbSizeHeight + (percentage * (bounds.size.width - (2 * thumbSizeHeight)))
            let touchLocation = touch.location(in: self)
            return touchLocation.x <= (thumbPosition + thumbTouchSize.width) && touchLocation.x >= (thumbPosition - thumbTouchSize.width)
            }
    }

它的外观如下:

自定义UISlider初始状态

enter image description here

当拇指向右端移动时

enter image description here

自定义UISlider最大值值

enter image description here

如你所见, (1)我为轨道和拇指设置了相同的高度,但是拇指不在轨道的垂直中心,这看起来不太好。 (2)当我将滑块拉到右端时,边缘变得平坦,这不应该发生(边缘应始终像初始状态一样保持圆形)。

我尝试了所有建议的解决方案,没有解决我的问题。请提前帮助,非常感谢。

0 个答案:

没有答案