UISlider Handle Changes Width on Different Size iP

2019-06-04 21:40发布

问题:

I have a vertical slider which uses the following code to generate a handle image within its custom class:

func generateHandleImage(with color: UIColor) -> UIImage {


    let rect = CGRect(x: 0, y: 0, width: (superview?.bounds.size.height)! * 0.07,
                      height: (superview?.bounds.size.width)!)


    return UIGraphicsImageRenderer(size: rect.size).image { (imageContext) in
        imageContext.cgContext.setFillColor(color.cgColor)
        imageContext.cgContext.fill(rect.insetBy(dx: 0, dy: 0))
    }
}

I have set the autolayout constraints in IB for the slider for it to be centered in the x & y axes of it's superview and equal widths and heights with the heights and widths of it's superview (since it is a vertical slider).

this is the code which makes my slider vertical and calls the function to generate the handle image:

// Make Sliders Vertical
    let sliderTransform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2) + CGFloat(M_PI))
    pitchBendSlider.transform = sliderTransform

    pitchBendSlider.setThumbImage(pitchBendSlider.generateHandleImage(with: .white), for: .normal)

I want the handle image to be equal to the width of it's superview. It does this correctly on an iPad Air 2 in iOS simulator, but on an iPad Pro 12.9" it is about 80-90% of the superview's width, and on an iPad Air it is slightly bigger than the superview's width.

How can I make the width of the custom slider's image handle equal to it's superview's width on all iPad sizes?

回答1:

Through trial & error I discovered this was a "timing issue". The handle image rect was being drawn too soon in viewDidLoad.

My "hack" solution was to place the function that draws the slider handle into the button action function which calls the views to appear (which has the vertical slider inside it).

Adding a timing delay would probably solve the problem just the same. Both are hack solutions, and I still lack the understanding of why the proper screen size is not recognized prior to viewDidLoad being called in the VC which contains the vertical slider...

However, this solved the problem.