创建圆角时如何在UITextField Swift中添加边框

时间:2019-04-18 17:44:33

标签: ios swift uitextfield

我想创建一个圆角“椭圆形” UITextField。我的内边框没有四舍五入,并且当UITextField的背景与视图相同时,给UITextField提供了奇怪的日志

边框的外观:

 how border look like

我想实现的来自MockAUp的图像:

Image from the MockAUp what I want to achieve

快捷代码:

txtfEmail.layer.cornerRadius = 26
txtfEmail.clipsToBounds = true
txtfEmail.attributedPlaceholder =  NSAttributedString(string: "Email",
                                                      attributes: [NSAttributedString.Key.foregroundColor: UIColor.white.withAlphaComponent(0.5)])

通过电子邮件发送UITextfield检查器

enter image description here

3 个答案:

答案 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
    }

}

故事板/界面生成器中的结果:

enter image description here

答案 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