【问题标题】:Problem in setting bottom border for UITextField in swift 5在 swift 5 中为 UITextField 设置底部边框的问题
【发布时间】:2020-05-10 04:04:01
【问题描述】:

我是 swift 新手。我有两个 UITextFields emailpassword。我只想为文本字段添加底部边框,为此我使用以下方法,

extension UITextField {

    func setBottomBorderWithLayer() {
        self.borderStyle = .none

        self.layer.masksToBounds = false
        self.layer.shadowColor = UIColor.gray.cgColor
        self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        self.layer.shadowOpacity = 1.0
        self.layer.shadowRadius = 0.0
      }

}

这就是我调用方法的方式

emailTextField.setBottomBorderWithLayer()
passwordTextField.setBottomBorderWithLayer()

现在的问题是 setBottomBorderWithLayer() 方法只为 emailTextField 设置底部边框,而不为 passwordTextField 设置底部边框。 谁能解释一下问题出在哪里?

提前致谢。

【问题讨论】:

  • 代码看起来很合理,显然你如何配置/布局这两个字段导致只有一个失败......我会尝试比较你正在做的两个看看不同之处可能是 UI 调试器也可能有助于为您提供一些线索。
  • 阴影不是边框;如果目标是为文本字段添加底部边框线,您为什么不实际这样做

标签: ios swift swift5


【解决方案1】:

我同意 Silas 的观点,但在这里补充一下…… 如果您想为文本字段创建一个彩色底栏,这也可以:

import Foundation
import UIKit

class Utilities {

static func styleTextField(_ textfield:UITextField) {

    // Create the bottom line
    let bottomLine = CALayer()

    bottomLine.frame = CGRect(x: 0, y: textfield.frame.height - 2, width: textfield.frame.width, height: 2)

    bottomLine.backgroundColor = UIColor.init(red: 116/255, green: 203/255, blue: 128/255, alpha: 1).cgColor

    // Remove border on text field
    textfield.borderStyle = .none

    // Add the line to the text field
    textfield.layer.addSublayer(bottomLine)

}

【讨论】:

    【解决方案2】:

    我们需要更多详细信息才能确定错误所在,但我建议另一种实现方式满足您的需求。

    创建一个从UITextField扩展的类,在这个类中你可以定义所有必要的布局设置便于重用,因为您只需要在 Storyboard -> TextField -> Identity Inspector -> Custom Class -> Class 中定义 TextField 中的类。

    类示例:

    import UIKit
    
    class BottomBorderTextField: UITextField {
    
        override init (frame: CGRect) {
            super.init (frame: frame)
            addBottomBorder()
        }
    
        required init? (coder: NSCoder) {
            super.init (coder: coder)
            addBottomBorder()
        }
    
        func addBottomBorder() {
            // Logic for adding style
    
            layer.backgroundColor = UIColor.white.cgColor
            layer.borderColor = UIColor.gray.cgColor
            layer.borderWidth = 0.0
            layer.cornerRadius = 5
            layer.masksToBounds = false
            layer.shadowRadius = 2.0
            layer.shadowColor = UIColor.black.cgColor
            layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
            layer.shadowOpacity = 1.0
            layer.shadowRadius = 1.0
        }
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多