swiftintslidersenderaddtarget

A programmatically UISlider not changing width


My swift code is all code no storyboard. My slider sx should change the width of the imagview when the value is changed. That is not happening no change is visible on the imageview. The imageview should increase / decrease when the slider value is changed.

    import UIKit

class ViewController: UIViewController {

var sx = UISlider()
var pic = UIImageView()
var ww = 80

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    [sx,pic].forEach{
        $0.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview($0)
        $0.backgroundColor = UIColor.systemPink
    }
    pic.frame = CGRect(x: view.center.x-115, y: view.center.y-200, width: CGFloat(ww), height: 50)
    sx.frame = CGRect(x: view.center.x-115, y: view.center.y + 200, width: 80, height: 50)

    sx.addTarget(self, action: #selector(ji), for: .valueChanged)
}


@objc func ji(sender : UISlider){
    ww = Int(sx.value)
}

}

Solution

  • Reset frame inside ji function as code inside viewDidLoad won't be triggered again it's called only once when the vc is loaded

    @objc func ji(sender : UISlider){
       ww = Int(sx.value)! * 80  
       pic.frame = CGRect(x: view.center.x-115, y: view.center.y-200, width: CGFloat(ww), height: 50)
    }