我想创建一个圆角“椭圆形” UITextField。我的内边框没有四舍五入,并且当UITextField的背景与视图相同时,给UITextField提供了奇怪的日志
边框的外观:
我想实现的来自MockAUp的图像:
快捷代码:
txtfEmail.layer.cornerRadius = 26
txtfEmail.clipsToBounds = true
txtfEmail.attributedPlaceholder = NSAttributedString(string: "Email",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white.withAlphaComponent(0.5)])
通过电子邮件发送UITextfield检查器
答案 0 :(得分:0)
您应该这样创建圆形边框:
txtfEmail.layer.cornerRadius = txtfEmail.height / 2
txtfEmail.layer.borderWidth = 1
txtfEmail.layer.borderColor = UIColor.black.cgColor
好像边框设置为文本字段下的视图
答案 1 :(得分:0)
一种方法是使用嵌入的文本字段创建自定义UIView
类。
下面是一个示例,使用@IBInspectable
和@IBDesignable
在情节提要设计期间让您看到它:
import UIKit
@IBDesignable
class RoundedTextField: UIView {
@IBInspectable var placeholder: String = "" {
didSet {
textField.attributedPlaceholder = NSAttributedString(string: placeholder,
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white.withAlphaComponent(0.5)])
}
}
let textField: UITextField = {
let v = UITextField()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func prepareForInterfaceBuilder() {
commonInit()
}
func commonInit() -> Void {
layer.borderColor = UIColor.white.cgColor
layer.borderWidth = 2
layer.masksToBounds = true
addSubview(textField)
NSLayoutConstraint.activate([
textField.topAnchor.constraint(equalTo: topAnchor, constant: 12.0),
textField.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -12.0),
textField.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20.0),
textField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20.0),
])
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.size.height * 0.5
}
}
故事板/界面生成器中的结果:
答案 2 :(得分:0)
尝试一下对我有用 打开情节提要 拖放文本字段 ctrl单击并在视图控制器中创建一个插座,并命名为可以说出emailfield 然后写这段代码
@iboultet weak var emailfield: uitextfield!{
didset{
emailfield.layer.masktobounds = true
emailfield.layer.cornerradius = 26
emailfield.layer.borderwidth = 1
emailfield.backgroundcolor = whatever color you want