swift2 TextField图标前的填充

ncgqoxb0  于 2022-11-06  发布在  Swift
关注(0)|答案(5)|浏览(184)

我得到了在textfield以编程方式启动之前应用图标的方法,但主要关注的是在图标之前应用填充。
因为它刚好接触到文本字段的边框。
我的程序如下:

override func viewWillAppear(animated: Bool) {

    // Email Icon on left of email Text Field
    let imageView1 = UIImageView()
    let image1 = UIImage(named: "Message.png")
    imageView1.image = image1
    imageView1.frame = CGRectMake(100, 0, 10, 10)
    emailTextField.leftView = imageView1
    emailTextField.leftViewMode = UITextFieldViewMode.Always

    // Password Icon on left of pass Text Field
    let imageView2 = UIImageView()
    let image2 = UIImage(named: "Lock.png")
    imageView2.image = image2
    imageView2.frame = CGRectMake(100, 0, 10, 10)
    passwordTextField.leftView = imageView2
    passwordTextField.leftViewMode = UITextFieldViewMode.Always

}

但是一路上边框和图标之间的空间非常小。
有没有办法在它们之间做一个衬垫?
如果有什么办法请告诉我。

30byixjq

30byixjq1#

1.尝试创建一个UI视图(例如contentView)和一个UI图像视图(例如leftImage
1.将 leftImage 帧设置为与 * contentView * 的x相距10点对齐(即,如果 contentView 的帧为(0,0,25,20),则将 leftImage 的帧设置为(10,0,15,20))
1.然后将 leftImage 作为子视图添加到 contentView
1.现在很简单,添加 contentView 作为文本字段的leftView。

let leftImage = UIImageView()

let image1 = UIImage(named: "Key")
leftImage.image = image1

let contentView = UIView()
contentView.addSubview(leftImage)

contentView.frame = CGRectMake(0, 0, 25, 20)
leftImage.frame = CGRectMake(10, 0, 25, 20)

passwordTextField.leftView = contentView
passwordTextField.leftViewMode = UITextFieldViewMode.Always

上一个输出:

最终输出:

m0rkklqb

m0rkklqb2#

你可以取一个宽度为20的UIView,然后把leftVeiw添加到这个视图中。现在把这个视图设置为leftView

u91tlkcl

u91tlkcl3#

您可以通过继承UITextField来轻松调整间距

class field: UITextField {

override func leftViewRectForBounds(bounds: CGRect) -> CGRect {
    var rect = bounds
    rect.origin.x -= 10
    return rect
}

override func textRectForBounds(bounds: CGRect) -> CGRect {
    var rect = bounds
    rect.origin.x -= 10
    return rect
}

}
ukxgm1gy

ukxgm1gy4#

只需在一行中完成

textfield.layer.sublayerTransform = CATransform3DMakeTranslation(10.0f, 0.0f, 0.0f);
nbysray5

nbysray55#

class ViewController: UIViewController {

    @IBOutlet weak var passTextfield: UITextField!
    @IBOutlet weak var emailTextfield: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let emailImage = UIImage(named:"email")
        addLeftImageTo(txtfield: emailTextfield, andImage:emailImage!)

        let passwordImage = UIImage(named:"password")
        addLeftImageTo(txtfield: passTextfield, andImage:passwordImage!)
    }

    func addLeftImageTo(txtfield:UITextField,andImage img:UIImage) {
        let leftImageView=UIImageView(frame:CGRect(x:10, y: 0, width: 25, height: 20))
        leftImageView.image=img

        let view = UIView(frame: CGRect(x: 0, y: 0, width: 35, height: 20))
       view.addSubview(leftImageView)

        txtfield.leftView=view
        txtfield.leftViewMode = .always

相关问题