我有一个5部分的滑块,我想为这部分跳过!我这样做了:
@IBAction func changeCostSlider(_ sender: UISlider) {
sender.value = roundf(costSlider.value)
}
我还想在滑块的拇指上添加标签,我尝试将此代码添加到上面的代码中:
let trackRect: CGRect = costSlider.trackRect(forBounds: costSlider.bounds)
let thumbRect: CGRect = costSlider.thumbRect(forBounds: costSlider.bounds , trackRect: trackRect, value: costSlider.value)
let x = thumbRect.origin.x + costSlider.frame.origin.x
let y = costSlider.frame.origin.y - 20
sliderLabel.center = CGPoint(x: x, y: y)
但是当我移动我的滑块时,我的标签从我将标签放在故事板中的位置跳转,并且它有一些滞后!有人建议如何将这个标签添加到我的步骤滑块并正常工作吗?!
我认为我的问题是我将我的UILable固定在storyborad中,当我在滑块中移动拇指时,为了mili秒,它会回到固定位置!我怎么解决呢?!
我试图以编程方式添加我的UILabel,直到我触摸拇指才能正常工作!它是如何完成的:
var sliderLableP = UILabel()
@IBAction func changeCostSlider(_ sender: UISlider) {
sender.value = roundf(costSlider.value)
print(costSlider.value)
let trackRect: CGRect = costSlider.trackRect(forBounds: costSlider.bounds)
let thumbRect: CGRect = costSlider.thumbRect(forBounds: costSlider.bounds , trackRect: trackRect, value: costSlider.value)
let x = thumbRect.origin.x + costSlider.frame.origin.x
let y = costSlider.frame.origin.y - 20
sliderLableP.center = CGPoint(x: x, y: y)
}
在我的viewDidLoad中我添加了这个:
sliderLableP = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
let trackRect: CGRect = costSlider.trackRect(forBounds: costSlider.bounds)
let thumbRect: CGRect = costSlider.thumbRect(forBounds: costSlider.bounds , trackRect: trackRect, value: costSlider.value)
let x = thumbRect.origin.x + costSlider.frame.origin.x
let y = costSlider.frame.origin.y - 20
sliderLableP.center = CGPoint(x: x, y: y)
sliderLableP.textAlignment = NSTextAlignment.center
sliderLableP.textColor = UIColor.blue
self.containerView.addSubview(sliderLableP)
containerView.bringSubview(toFront: sliderLableP)
答案 0 :(得分:5)
此解决方案适用于我:
@IBAction func changeCostSlider(_ sender: UISlider) {
sender.value = roundf(sender.value)
let trackRect = sender.trackRect(forBounds: sender.frame)
let thumbRect = sender.thumbRect(forBounds: sender.bounds, trackRect: trackRect, value: sender.value)
self.sliderLabel.center = CGPoint(x: thumbRect.midX, y: self.sliderLabel.center.y)
}
答案 1 :(得分:0)
我已经创建了 UISlider 的扩展。
extension UISlider {
func setThumbValueWithLabel() -> CGPoint {
let slidertTrack : CGRect = self.trackRect(forBounds: self.bounds)
let sliderFrm : CGRect = self.thumbRect(forBounds: self.bounds, trackRect: slidertTrack, value: self.value)
return CGPoint(x: sliderFrm.origin.x + self.frame.origin.x + 8, y: self.frame.origin.y - 20)
}
}
这是你如何使用它:-
step1:- 在 UISlider 的 .valueChanged 属性上添加目标操作。
self.slider.addTarget(self, action: #selector(sliderValueChanged),for: .valueChanged)
step2:- 在sliderValueChanged() 方法上,使用扩展方法。
@objc private func sliderValueChanged(_ sender: UISlider) {
self.yourLabel.text = Int(sender.value).description
self.yourLabel.center = sender.setThumbValueWithLabel()
}