Search code examples
iosswiftuitextfieldrightviewskyfloatinglabeltextfield

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? It is not aligning vertically centre with the text of the textfield.


Solution

  • 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

    enter image description here