sách gpt4 ăn đã đi

ios - UITextField 标准样式以编程方式

In lại 作者:搜寻专家 更新时间:2023-11-01 06:58:43 24 4
mua khóa gpt4 giày nike

当我使用 Storyboard创建一个 UITextField 时,它看起来像下图。但是,当我以编程方式创建 UITextField 时,它完全没有样式。我知道我可以将自定义样式应用到文本字段,但是在以编程方式创建文本字段时是否有一种简单的方法来获取此标准样式?

UITextField

câu trả lời hay nhất

Như thế này:

let t = UITextField()
t.frame = CGRect(x: 10, y: 20, width: self.view.frame.width - 20, height: 40)
t.layer.cornerRadius = 5
t.layer.borderColor = UIColor.lightGray.cgColor
t.layer.borderWidth = 1
t.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: t.frame.height))
t.leftViewMode = .always
t.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: t.frame.height))
t.rightViewMode = .always
t.clearButtonMode = .whileEditing
self.view.addSubview(t)

biên tập:

在某处添加此类,以便于/全局访问它。

class StyledTextField: UITextField { 
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = 5
self.layer.borderColor = UIColor.lightGray.cgColor
self.layer.borderWidth = 1
self.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: t.frame.height))
self.leftViewMode = .always
self.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: t.frame.height))
self.rightViewMode = .always
self.clearButtonMode = .whileEditing
}
}

然后你可以从任何你想要的地方调用这个UITextField

let t = StyledTextField()
t.frame = CGRect(x: 10, y: 20, width: self.view.frame.width - 20, height: 40)
self.view.addSubview(t)

Chỉnh sửa 2:

sử dụng UIEdgeInsets 在所有四个边上填充。

class StyledTextField: UITextField { 
let insetConstant = UIEdgeInsets(top: 4, left: 10, bottom: 4, right: 10)

override func textRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, insetConstant)
}

override func editingRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, insetConstant)
}

override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, insetConstant)
}

override init(frame: CGRect) {
super.init(frame: frame)

self.layer.cornerRadius = 5
self.layer.borderColor = UIColor(white: 2/3, alpha: 0.5).cgColor
self.layer.borderWidth = 1
self.clearButtonMode = .whileEditing
self.keyboardType = UIKeyboardType.decimalPad
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

关于ios - UITextField 标准样式以编程方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51872525/

24 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress