-1

I placed a UITextField inside a UIView and set textField.autoresizingMask = [.flexibleWidth, .flexibleHeight] (no autoLayout used). I also attached a UISlider to change the frame of UIView. As I have set autoresizingMask with UIView, UITextField size increase as well as. But issue is text is bounces heavily when I change UIView's bounds. I tried to look into this SO answer and called layoutIfNeeded() for bounds update call but it doesn't stop bouncing.

Here is a video demo

EDIT

I have implemented textField without being on subView. Even I did not set autoresizingMask this time. But still textField is bouncing on. Here is Demo code snippet and also Demo project

sz ashik
  • 881
  • 7
  • 20
  • It looks like you're changing the frame to sizes where the height is not evenly divisible, so the centerY position changes slightly. You probably need to modify your sizing code to make sure the textField stays in place. – DonMag Jul 11 '19 at 13:57
  • sorry, couldn't get the `evenly divisible` part. Is it because the height of UIView is not being even when frame is changing? – sz ashik Jul 11 '19 at 14:20
  • Yes... elements cannot be on "partial pixels". So, if your size changes so that the **Y point** position causes the **Y pixel** position to be, say, 200.5, it will be rounded off. If you restrict your view height changes to even numbers (change by 2 instead of by 1), you probably won't see the bouncing. – DonMag Jul 11 '19 at 15:03
  • Thanks @DonMag, After spending lots of times I have found that textField bounces if I don't center it or put it on a sub-view. PS: I have edited my Question – sz ashik Jul 12 '19 at 10:21

1 Answers1

0

Give this a try.

It rounds the new width and height to the nearest even number. This makes sure the label / textField can be centered consistently.

@IBAction func sizeChange(_ sender: UISlider) {
    let scaleFactor = CGFloat(sender.value)
    // CGAffineTransform will rastarize the text and make it blurry
    // selectedView.transform = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)

    let baseSize = isLabelSelected ? labelBaseSize : textFielBasedSize

    let actualWidth = baseSize!.width * scaleFactor
    let roundedWidth = CGFloat(Int(round(actualWidth / 2.0)) * 2)

    let actualHeight = baseSize!.height * scaleFactor
    let roundedHeight = CGFloat(Int(round(actualHeight / 2.0)) * 2)

    selectedView.bounds = CGRect(x: selectedView.bounds.origin.x,
                                 y: selectedView.bounds.origin.y,
                                 width: roundedWidth,
                                 height: roundedHeight)

    //selectedView.bounds = CGRect(x: selectedView.bounds.origin.x,
    //                           y: selectedView.bounds.origin.y,
    //                           width: baseSize!.width * scaleFactor,
    //                           height: baseSize!.height * scaleFactor)

}
DonMag
  • 69,424
  • 5
  • 50
  • 86