将UIImageView垂直对齐添加为textfield的rightView和skyfloatinglabeltextfield的文本

时间:2018-05-18 06:43:18

标签: ios swift uitextfield rightview skyfloatinglabeltextfield

我添加了一个checkmarkImageView作为skyfloatinglabeltextfield的右视图,如下所示:

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.

3 个答案:

答案 0 :(得分:2)

更改frame.offsetBy,我使用textfield Border Style作为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

<强>输出

enter image description here

答案 1 :(得分:1)

尝试将checkmarkImageView的框架更改为:

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

请添加您从UI调试器获取的帧的屏幕截图。

修改

checkmarkImageView?.contentMode = .scaleAspectFit

编辑-2:

要获得文本的高度,请使用:

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

根据您的要求添加属性。

如果您仍然遇到任何问题,请告诉我。

答案 2 :(得分:0)

也许您可以使用该功能:

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
}

最好的问候