如何使用 UISlider 更新 UIView 宽度?

How can I update a UIView width with a UISlider?

我正在尝试使用滑块更改 UIView 的宽度。我的问题是我的代码不是更新视图宽度而是添加新视图。我不知道如何使用 swift 游乐场更新视图。

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

    var feelings01Slider: UISlider!
    var feelingsWidth01 = 100

    var dayFeelings01: UIView!
    var dayFeelings02: UIView!
    var dayFeelings03: UIView!

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white
        self.view = view

        feelings01Slider = UISlider()
        feelings01Slider.frame = CGRect(x: 62, y: 375, width: 250, height: 20)
        feelings01Slider.minimumValue = 1
        feelings01Slider.maximumValue = 248
        feelings01Slider.value = 100
        feelings01Slider.isContinuous = true

        feelings01Slider.addTarget(self, action: #selector(sliderValueDidChange(sender:)), for: .valueChanged)
        setUpFeelings()

        view.addSubview(feelings01Slider)
    }

    func setUpFeelings() {

        feelingsWidth01 = Int(feelings01Slider.value)
        var feelingsX02 = feelingsWidth01 + 62
        var feelingsWidth02 = 80
        var feelingsX03 = feelingsX02 + feelingsWidth02
        var feelingsWidth03 = 70

        dayFeelings01 = UIView(frame: CGRect(x: 62, y: 100, width: feelingsWidth01, height: 250))
        dayFeelings01.backgroundColor = .yellow

        dayFeelings02 = UIView(frame: CGRect(x: feelingsX02, y: 100, width: feelingsWidth02, height: 250))
        dayFeelings02.backgroundColor = .blue

        dayFeelings03 = UIView(frame: CGRect(x: feelingsX03, y: 100, width: feelingsWidth03, height: 250))
        dayFeelings03.backgroundColor = .red

        view.addSubview(dayFeelings01)
        view.addSubview(dayFeelings02)
        view.addSubview(dayFeelings03)

    }

    @objc func sliderValueDidChange(sender:UISlider) {
        feelingsWidth01 = Int(sender.value)
        dayFeelings03.removeFromSuperview()
        dayFeelings02.removeFromSuperview()
        dayFeelings01.removeFromSuperview()
        setUpFeelings()
    }


}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

我是编程新手,如果我的代码看起来很乱,请见谅。

您不需要用不同大小的新视图替换视图。你可以改变他们的框架。将您的滑块选择器操作替换为:

@objc func sliderValueDidChange(sender:UISlider) {
    dayFeelings01.frame.size.width = CGFloat(sender.value)
}

注意:因为黄色视图是第一个添加的,它正在下面其他视图展开。这就是为什么你看不到它变宽的原因。尝试更改顺序,使其最后添加,您会看到它。如果您希望其他视图适应可用 space,您也可以更新它们的框架,UIStackView 可能会使这变得容易。

祝你好运!