I'm trying to make a slider resize my images and center them into a view. I've tried all kinds of stuff, but am left with this after deleting all the non working code. I have the image Horizontal and Vertically lined up with constraints in the storyboard, but doesn't seem to help. Here is the crappy code I have.
@IBAction func sizeSlider(_ sender: UISlider) {
let value = Int(sender.value)
var sizeValue:Int = 200
switch value {
case 0...1:
sizeLabel.text = "100x100"
sizeValue = 100
case 2:
sizeLabel.text = "150x150"
sizeValue = 150
case 3:
sizeLabel.text = "200x200"
sizeValue = 200
case 4:
sizeLabel.text = "250x250"
sizeValue = 250
case 5:
sizeLabel.text = "300x300"
sizeValue = 300
default:
print("Error")
}
dartBoardImage.frame.size.width = CGFloat(sizeValue)
dartBoardImage.frame.size.height = CGFloat(sizeValue)
}
"I have the image Horizontal and Vertically lined up with constraints in the storyboard"
You cannot mix auto-layout (constraints) with explicit frame
changes.
What you (probably) want to do is...
In Storyboard:
dartBoardImage
image view a Width constraint of 100
1:1
... that will keep it's height equal to its widthNow, Ctrl-Drag from the Width constraint to your class code, and create an outlet for it:
@IBOutlet var imageWidthConstraint: NSLayoutConstraint!
Your slider code will now change that constraint's .constant
property to update the size:
imageWidthConstraint.constant = CGFloat(sizeValue)
So, your full sizeSlider
func becomes:
@IBAction func sizeSlider(_ sender: UISlider) {
let value = Int(sender.value)
var sizeValue:Int = 200
switch value {
case 0...1:
sizeLabel.text = "100x100"
sizeValue = 100
case 2:
sizeLabel.text = "150x150"
sizeValue = 150
case 3:
sizeLabel.text = "200x200"
sizeValue = 200
case 4:
sizeLabel.text = "250x250"
sizeValue = 250
case 5:
sizeLabel.text = "300x300"
sizeValue = 300
default:
print("Error")
}
// change the image view's width constraint
imageWidthConstraint.constant = CGFloat(sizeValue)
// don't do this
//dartBoardImage.frame.size.width = CGFloat(sizeValue)
//dartBoardImage.frame.size.height = CGFloat(sizeValue)
}