如何在iOS中创建图像和文本字段之间的空间

时间:2017-04-19 08:29:54

标签: ios swift user-interface uitextfield

我试图在UITextField中保留图像和文本之间的空格。我有这个:

self.txtUsername.leftViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: "icoUserName")
imageView.image = image
self.txtUsername.leftView = imageView

这成功添加了一张图片,但我希望它们之间的间隙更少。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

尝试按左下​​方添加:

let envelopeView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
 let image = UIImage(named: "icoUserName")
envelopeView.image = image
var viewLeft: UIView = UIView(frame: CGRectMake(20, 0, 30, 30))// set per your requirement
viewLeft.addSubview(envelopeView)
textField.leftView = viewLeft
textField.leftViewMode = UITextFieldViewModeAlways

Swift 3.0

let envelopeView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        let image = UIImage(named: "icoUserName")
        envelopeView.image = image
        let viewLeft: UIView = UIView(frame: CGRect(x: 20, y: 0, width: 30, height: 30))// set per your requirement
        viewLeft.addSubview(envelopeView)
        txtUsername.leftView = viewLeft
        txtUsername.leftViewMode = UITextFieldViewMode.always

答案 1 :(得分:0)

Swift 3.0

尝试按左下​​方添加:

let envelopeView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        let image = UIImage(named: "icoUserName")
        envelopeView.image = image
        let viewLeft: UIView = UIView(frame: CGRect(x: 20, y: 0, width: 30, height: 30))// set per your requirement
        viewLeft.addSubview(envelopeView)
        txtUsername.leftView = viewLeft
        txtUsername.leftViewMode = UITextFieldViewMode.always