我有以下UICollectionViewCell子类,我在没有使用故事板的情况下创建了UISlider:
class ProductDetailPersonalLoanViewCell: UICollectionViewCell {
let valueSlider: UISlider = {
let mySlider = UISlider(frame:CGRect(x: 10, y: 100, width: 300, height: 20))
mySlider.isUserInteractionEnabled = true
mySlider.minimumValue = 0
mySlider.maximumValue = 100
mySlider.isContinuous = true
mySlider.tintColor = UIColor.green
mySlider.addTarget(self, action: #selector(sliderValueDidChange(_:)), for: .valueChanged)
return mySlider
}()
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
}
func setupViews(){
addSubview(valueSlider)
// ....... layout constraints
}
func sliderValueDidChange(_ sender:UISlider!){
print("Slider value changed")
let roundedStepValue = round(sender.value / step) * step
sender.value = roundedStepValue
print("Slider step value \(Int(roundedStepValue))")
}
}
问题在于,由于某种原因,当我移动拇指时没有触发事件,所以我无法使用UISlider值。有人知道如何解决这个问题吗?
答案 0 :(得分:1)
您必须在计算值块之外的valueSlider
添加目标:
let valueSlider: UISlider = {
let mySlider = UISlider(frame:CGRect(x: 10, y: 100, width: 300, height: 20))
mySlider.isUserInteractionEnabled = true
mySlider.minimumValue = 0
mySlider.maximumValue = 100
mySlider.isContinuous = true
mySlider.tintColor = UIColor.green
return mySlider
}()
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
valueSlider.addTarget(self, action: #selector(sliderValueDidChange(_:)), for: .valueChanged)
}
或者,我认为这是一个更好的解决方案,将计算值更改为惰性属性:
lazy var valueSlider: UISlider = {
let mySlider = UISlider(frame:CGRect(x: 10, y: 100, width: 300, height: 20))
mySlider.isUserInteractionEnabled = true
mySlider.minimumValue = 0
mySlider.maximumValue = 100
mySlider.isContinuous = true
mySlider.tintColor = UIColor.green
mySlider.addTarget(self, action: #selector(sliderValueDidChange(_:)), for: .valueChanged)
return mySlider
}()
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
}