我有一个UIControl
的子类
我想要实现的是UISlider
与UIButton
- 像拇指一样
但如果我使用
,我会感到很沮丧的touchesBegan(::)
或
beginTrackingWithTouch(::)
如何强制我的按钮跟随触摸事件 我刚刚实现的是突出显示一个按钮,覆盖其 @highlighted属性,如下所示:
class RangeSliderThumbLayer: UIButton {
override var highlighted: Bool {
didSet {
//print("did set \(highlighted)")
setNeedsDisplay()
if highlighted {
self.backgroundColor = UIColor.redColor()
} else {
self.backgroundColor = UIColor.greenColor()
}
}
}
这里我试图移动我的按钮:
let lowerThumbButton = RangeSliderThumbLayer(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let upperThumbButton = RangeSliderThumbLayer(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
previousLocation = touch.locationInView(self)
print(previousLocation)
lowerThumbButton.frame = CGRectMake(previousLocation.x, 0, 20, 20)
// Hit test the thumb layers
if lowerThumbButton.pointInside(previousLocation, withEvent: event) {
print("point indide")
lowerThumbButton.highlighted = true
} else if upperThumbButton.frame.contains(previousLocation) {
upperThumbButton.highlighted = true
}
return lowerThumbButton.highlighted || upperThumbButton.highlighted
}
private func boundValue(value: Double, toLowerValue lowerValue: Double, upperValue: Double) -> Double {
return min(max(value, lowerValue), upperValue)
}
override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let location = touch.locationInView(self)
let value = round(location.x / step)
let validValue = minimumValue + (Double(value) * increase)
let deltaLocation = Double(location.x - previousLocation.x)
print(value)
lowerThumbButton.frame = CGRectMake(value, 0, 20, 20)
previousLocation = location
if lowerThumbButton.highlighted {
lowerValue = boundValue(validValue, toLowerValue: minimumValue, upperValue: upperValue)
} else if upperThumbButton.highlighted {
upperValue = boundValue(validValue, toLowerValue: lowerValue, upperValue: maximumValue)
}
return true
}