Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS 13: spacing Issue with UITextField rightView

Tags:

I am facing a spacing issue with a right view of UITextField in IOS 13, See my following code and screenshot of ios 13 and ios 12.4

In IOS 12.4 simulator display proper space in the right view (UIButton)of UITextField

In IOS 13.0 simulator has a spacing issue in the right view (UIButton)of UITextField

let dropdownButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: txtField.frame.height)) dropdownButton.backgroundColor = UIColor.clear dropdownButton.setImage(UIImage(named: "ic_DownArrow"), for: UIControl.State())             txtField.rightView = dropdownButton            txtField.rightViewMode = .always 

enter image description here enter image description here

like image 872
AtulParmar Avatar asked Sep 30 '19 10:09

AtulParmar


2 Answers

Apparently this was a change in the way rightViewRect(forBounds:) behaves in iOS 13 Beta 5.

From the iOS & iPadOS 13 Developer Beta 5 Release Notes:

UIKit - Resolved Issues

Prior to iOS 13, UITextField assumed that the frames of its leftView and rightView were correctly set when assigned and would never change. Starting in iOS 13, the implementation of leftViewRect(forBounds:) and rightViewRect(forBounds:) now ask the view for its systemLayoutSizeFitting(:). To achieve the previous behavior when linking against and running on iOS 13, add explicit sizing constraints on the view, wrap it in a plain UIView, or subclass the view and implement systemLayoutSizeFitting(:). (51787798)

So Add Auto-Layout constraints to your custom view that you added to the rightView

Example:-

override func rightViewRect(forBounds bounds: CGRect) -> CGRect {         return CGRect(x: bounds.width - 30, y: 0, width: 20 , height: bounds.height)     } 
like image 102
Bruno Vaillant Avatar answered Sep 21 '22 20:09

Bruno Vaillant


Set the width constraint for the leftView or rightView you're adding.

leftImageView.widthAnchor.set(to: 30.0) textField.leftView = leftImageView textField.leftViewMode = .always 

Here's the extension I use to set the width constraint:

extension NSLayoutDimension {  @discardableResult func set(         to constant: CGFloat,         priority: UILayoutPriority = .required         ) -> NSLayoutConstraint {          let cons = constraint(equalToConstant: constant)         cons.priority = priority         cons.isActive = true         return cons     } } 
like image 27
Abdurrahman Avatar answered Sep 21 '22 20:09

Abdurrahman