如何在Swift 4中创建文本字段填充? [英] How do you create textfield padding in Swift 4?
问题描述
我有一个名为
nameTextField
我用
nameTexfield.layer.cornerRadius = 5
现在,文本字段中的文本正在触摸左侧.我想在文本和边框之间创建填充.我发现的每个帖子都使用cgRect,但是Swift不再支持该功能.如果可以解决,请提供正确的代码,如果可以,请解释答案.感谢您的帮助!我还需要知道如果有的话将代码放在哪里.
Now, the text within the textfield is touching the left side. I want to create padding between the text and border. Every post I find uses cgRect, but Swift no longer supports that. Please provide the correct code if you can figure it out and please explain the answer if you can. I appreciate the help! I also need to know where to put the code if there is any.
推荐答案
正如@ the4kman所说,Swift 确实支持CGRect
,但是语法可能已更改.
As @the4kman says, Swift does support CGRect
but the syntax may have changed.
您可以尝试以下操作:
@IBOutlet weak var nameTextField: UITextField! {
didSet {
nameTextField.layer.cornerRadius = 5
nameTextField.layer.borderColor = UIColor.black.cgColor
nameTextField.layer.borderWidth = 1
let leftView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 2.0))
nameTextField.leftView = leftView
nameTextField.leftViewMode = .always
}
}
如果我这样做,我会得到很好的结果
If I do that, I get this fine result
希望有帮助.
您要求的是功能而不是在didSet
中进行设置,请确保这是可能的,例如:
You ask for a function instead of setting it in didSet
and sure, thats possible, something like:
func addPaddingAndBorder(to textfield: UITextField) {
textfield.layer.cornerRadius = 5
textfield.layer.borderColor = UIColor.black.cgColor
textfield.layer.borderWidth = 1
let leftView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 2.0))
textfield.leftView = leftView
textfield.leftViewMode = .always
}
,然后在viewDidLoad
中调用它,例如:
and then you' call that in viewDidLoad
for instance like so:
override func viewDidLoad() {
super.viewDidLoad()
addPaddingAndBorder(to: nameTextField)
}
这篇关于如何在Swift 4中创建文本字段填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!