通过子类化在文本字段前添加空格

时间:2015-09-17 06:58:30

标签: ios swift textfield

所以我目前正在尝试在文本字段中添加一些空格。因此,当我输入时,它以四个空格而不是空格开头。所以我做了一些研究,我发现了一些似乎非常好的东西(如所有选票所示),即Create space at the beginning of a UITextField。一个问题是我不知道如何在我的其他类中实际实现它(假设这是帖子打算让读者做的事情)。

这是我认为我应该做的。我想我应该实例化该类的一个对象,并使用类中的方法在我的文本字段前面添加空格。但我实际上并不知道代码中的内容。谁能给我一个如何在这篇文章中实际实现代码的例子? Create space at the beginning of a UITextField

这是我到目前为止的代码:

import UIKit

class SignUpViewController: UIViewController {

    @IBOutlet weak var facebookButton: UIButton!
    @IBOutlet weak var googleplusButton: UIButton!
    @IBOutlet weak var fullNameTextField: UITextField!
    @IBOutlet weak var emailAddressTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        facebookButton.layer.cornerRadius = 5
        googleplusButton.layer.cornerRadius = 5

        fullNameTextField.layer.borderColor = UIColor.lightGrayColor().CGColor
        fullNameTextField.layer.borderWidth = 1.0
        emailAddressTextField.layer.borderColor = UIColor.lightGrayColor().CGColor
        emailAddressTextField.layer.borderWidth = 1.0
        passwordTextField.layer.borderColor = UIColor.lightGrayColor().CGColor
        passwordTextField.layer.borderWidth = 1.0

    }
}

2 个答案:

答案 0 :(得分:1)

您需要创建UITextField的子类。然后在其实现中添加此代码

static CGFloat leftMargin = 10;
- (CGRect)textRectForBounds:(CGRect)bounds
{
    bounds.origin.x += leftMargin;
    bounds.size.width -= (leftMargin + 20);
    return bounds;
}
- (CGRect)editingRectForBounds:(CGRect)bounds
{
    bounds.origin.x += leftMargin;
    bounds.size.width -= (leftMargin + 20);
    return bounds;
}

之后,将自定义类设置为UITextField

答案 1 :(得分:1)

您应该从@ScareCrow answer创建一个类。之后转到故事板并更改UITextField的类。如: Image

之后创建文本字段的IBOutlet。该出口将是TextField类的实例。

相关问题