coding22 coding22 - 5 months ago 8
iOS Question

Why is the position for my UISlider in my Iphone 4s different than all my other devices?

I positioned my slider in the middle of the screen and it is positioned correctly in all my devices except for the 4s. I cant figure out how to make it so that the slider is in the middle of the screen like all the other devices instead of to the right. Here is the code Im using:

enter image description here

if UIDevice.currentDevice().userInterfaceIdiom == .Phone {

let scaleFactor = UIScreen.mainScreen().bounds.width / 320


middleSlider = UISlider(frame: CGRectMake(125 * scaleFactor, 153 * scaleFactor, 150, 50))
middleSlider.tintColor = UIColor.whiteColor()
middleSlider.minimumTrackTintColor = UIColor.whiteColor()
middleSlider.maximumTrackTintColor = UIColor.whiteColor()
middleSlider.value = 1.0
middleSlider.continuous = true
middleSlider.userInteractionEnabled = true
self.view?.addSubview(middleSlider)
}

if UIDevice.currentDevice().userInterfaceIdiom == .Pad {

let scaleFactor = UIScreen.mainScreen().bounds.width / 320
middleSlider = UISlider(frame: CGRectMake(130 * scaleFactor, 650, 200, 150))
middleSlider.tintColor = UIColor.whiteColor()
middleSlider.minimumTrackTintColor = UIColor.whiteColor()
middleSlider.maximumTrackTintColor = UIColor.whiteColor()
middleSlider.value = 1.0
middleSlider.continuous = true
middleSlider.userInteractionEnabled = true
self.view?.addSubview(middleSlider)

}

Answer

To center the Slider you can simply do as follows

middleSlider = UISlider(frame: CGRectMake(self.view.bounds.width/2 - 150/2, 153 * scaleFactor, 150, 50));

And it also will be centered for all devices.