简体   繁体   中英

Vertically align UIImageView added as rightView of textfield with the text of skyfloatinglabeltextfield

I have added a checkmarkImageView as rightview of a skyfloatinglabeltextfield as follows:

let checkmark = UIImage(named: "checkmark") 
checkmarkImageView = UIImageView(image: checkmark)
checkmarkImageView?.frame = CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0)
textfield?.rightView = checkmarkImageView
textfield?.rightViewMode = .always
editView.addSubview(textfield!)

It is not aligning vertically centre with the text of the textfield. How do I achieve that? 它没有与文本字段的文本垂直居中对齐。

change the frame.offsetBy , I used textfield Border Style as Plain

    let rightVie = UIView()
    rightVie.backgroundColor = UIColor.clear

   checkmarkImageView = UIImageView(image: UIImage(named: "checkmark")) // use your imageView
  //  checkmarkImageView?.frame = CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0)
   checkmarkImageView.frame = checkmarkImageView.frame.offsetBy(dx: 0, dy: -1 + textfield.titleHeight()/2)
    rightVie.frame = checkmarkImageView.frame
    rightVie.addSubview(checkmarkImageView)
    //use your textfield name
    textfield?.rightView = rightVie
    textfield?.rightViewMode = .always

output

在此处输入图片说明

Try changing the frame of checkmarkImageView to:

checkmarkImageView?.frame = CGRect(x: 0.0, y: 0.0, width: 20.0, height: textfield.bounds.height)

And please add a screenshot of the frames you are getting from the UI debugger.

Edit:

checkmarkImageView?.contentMode = .scaleAspectFit

Edit-2:

To get the height of the text, use:

let textHeight = text.size(withAttributes: [NSAttributedStringKey.font: UIFont.openSansBold(size: 10)]).height

Add the attributes according to your requirement.

Let me know if you still face any issues.

Maybe you can use that function:

func setupNavUI() {
    let addressTextField = UITextField(frame: CGRect(x: 0.0, y: 0.0, width: self.navigationItem.titleView?.frame.width ?? 100.0, height: 50.0))
    addressTextField.rightViewMode = .always
    let icon = FAKFontAwesome.sortDownIcon(withSize: 20.0)
    icon?.setAttributes([NSAttributedString.Key.foregroundColor : UIColor.lightGray])
    let image = icon?.image(with: CGSize(width: 20.0, height: 20.0))
    let imageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0))
    imageView.image = image
    let rightView = UIView(frame: CGRect(x: 0, y: 0, width: 20.0, height: 26.0))
    rightView.addSubview(imageView)
    addressTextField.rightView = rightView
    addressTextField.placeholder = "Buscar una dirección"
    self.navigationItem.titleView = addressTextField
}

Best Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM