I currently have an image and 2 strings that I add to a button and I add the button to a uiview that I add to the left side of a textField. I take the image and 2 strings and make one complete string by first converting the image to a NSTextAttachment and then appending the other 2 strings to the end of it.
It works but the problem is the image (downArrow) is too big compared to the 2 strings and it appears to sit directly in the centerY of the textField while the 2 strings sit towards the lower bottom of the textField.
(the red background is just to highlight the uiview that I use that the button sits inside)
The emoji flag is a string not an image
I thought to myself maybe the best way to remedy this is to first set the downArrow image to the left side of the textField and then add the 2 strings to the button and put the button on the left side of the downArrow. The only problem with that is eventually I want the paddingView the button is in to be the exact width of all 3 strings so that width doesn't have all the empty space at the beginning and the end of the red view.
Just for clarity what I want to do is have the downArrow and the 2 strings line up vertically all on 1 line. Depending on the outcome of this I'll ask how to to get the width of all 3 in another question.
I tried setting the button's contentVerticalAlignment = .center
but it made no difference.
// button
var flagButton = UIButton()
flagButton.contentHorizontalAlignment = .fill
flagButton.contentVerticalAlignment = .center // I tried .fill too
flagButton.imageView?.contentMode = .scaleAspectFit // I tried .scaleAspectFill too
flagButton.setContentHuggingPriority(UILayoutPriority.defaultLow, for: .horizontal)
// downArrow, emoji flag, and dialing code that will get displayed inside the button
let emojiFlag = // emoji flag from string
let dialingCode = // country dialing code is a String
let flagAndDialingCode = "\(emojiFlag) \(dialingCode)"
let fullString = NSMutableAttributedString(string: " ", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20)])
let image1Attachment = NSTextAttachment()
image1Attachment.image = UIImage(named: "downArrow")
let image1String = NSAttributedString(attachment: image1Attachment)
fullString.append(image1String)
fullString.append(NSAttributedString(string: flagAndDialingCode))
flagButton.setAttributedTitle(fullString, for: .normal)
// button will go on the left side of this textField
phoneNumberTextField.layoutIfNeeded()
let height = phoneNumberTextField.frame.size.height
let width: CGFloat = 100 // this width should actually be the width of the image and 2 strings together
let frame = CGRect(x: 0, y: 0, width: width, height: height)
flagButton.frame = frame
let paddingView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
paddingView.backgroundColor = .red
paddingView.addSubview(flagButton)
phoneNumberTextField.leftViewMode = .always
phoneNumberTextField.leftView = paddingView