【问题标题】:How to only show bottom border of UITextField in Swift如何在 Swift 中只显示 UITextField 的底部边框
【发布时间】:2015-09-15 11:06:17
【问题描述】:

我想只显示底部边框并隐藏其他边。

输出我看到:如您所见,我也看到了顶部、左侧和右侧边框,它们是黑色的,我想删除它们。只需要底部白色粗2.0边框。

我正在使用的代码 (source):

var border = CALayer()
var width = CGFloat(2.0)
border.borderColor = UIColor.whiteColor().CGColor
border.frame = CGRect(x: 0, y: tv_username.frame.size.height - width, width: tv_username.frame.size.width, height: tv_username.frame.size.height)

border.borderWidth = width
tv_username.backgroundColor = UIColor.clearColor()
tv_username.layer.addSublayer(border)
tv_username.layer.masksToBounds = true
tv_username.textColor = UIColor.whiteColor()

【问题讨论】:

    标签: ios xcode swift uitextfield


    【解决方案1】:

    使用 Swift 5.1 尝试通过这种方式进行操作:

    var bottomLine = CALayer()
    bottomLine.frame = CGRect(x: 0.0, y: myTextField.frame.height - 1, width: myTextField.frame.width, height: 1.0)
    bottomLine.backgroundColor = UIColor.white.cgColor
    myTextField.borderStyle = UITextField.BorderStyle.none
    myTextField.layer.addSublayer(bottomLine)
    

    您必须将borderStyle 属性设置为None

    如果您使用自动布局,则设置完美约束,否则底线不会出现。

    希望对你有帮助。

    【讨论】:

    • 尝试了代码,但我看到所有边框都随着这段代码消失了。 (我的背景是蓝色的,不确定是否重要)。我希望底部边框只有白色。
    • @user1406716 检查这个:stackoverflow.com/questions/30701655/…我的回答
    • 意思是除了上面的 5 行之外,还需要什么额外的东西吗?我用它们只是用我的'tv_username` UITextField 替换myTextField
    • 我会将您的答案标记为答案,但我只需在我的问题中的代码中添加 this 行(因此您可能想为任何人编辑答案稍后阅读):myTextField.borderStyle = UITextBorderStyle.None
    • 设置“完美”约束是什么意思?
    【解决方案2】:

    从@Ashish 的回答中想到,很久以前在 Objective-C 中使用了相同的方法,但实现扩展会更有用。

    extension UITextField {
        func addBottomBorder(){
            let bottomLine = CALayer()
            bottomLine.frame = CGRect(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
            bottomLine.backgroundColor = UIColor.white.cgColor
            borderStyle = .none
            layer.addSublayer(bottomLine)
        }
    }
    

    在您的控制器中:

    self.textField.addBottomBorder()
    

    可以为您的方法添加更多参数,例如添加边框高度、颜色。

    【讨论】:

    • 谢谢。它对我有用。我还可以更进一步: extension UITextField { public func addBottomBorder(color: UIColor = UIColor.black, marginToUp: CGFloat = 1.00, height: CGFloat = 1.00){ let bottomLine = CALayer() bottomLine.frame = CGRect(x: 0, y: self.frame.size.height - marginToUp, width: self.frame.size.width, height: height) bottomLine.backgroundColor = color.cgColor borderStyle = .none layer.addSublayer(bottomLine) } }
    • 好答案。谢谢 iBug。
    【解决方案3】:

    @mina-fawzy 我喜欢 Mina Fawzy 的答案,其中包括 masksToBounds...

    我在尝试设置 UITextField 的底部边框时遇到了这个问题,而使用 CGRect 的 cmets 对我有用,然而,我在使用时遇到了问题不同的屏幕尺寸,或者如果我将方向从纵向更改为横向视图。

    即。我的 Xcode Main.storyboard 是使用 iPhone XS Max 设计的,UITextField 被限制为距屏幕左/右 20 点。在我的viewDidLoad() 中,我使用CGRect 方法对UITextField(文本字段)进行了样式化,使矩形的宽度等于textfield.frame.width

    在 iPhone XS Max 上进行测试时,一切正常,但是,当我在 iPhone 7(较小的屏幕宽度)上测试时,CGRect 在viewDidLoad() 期间抓取了 iPhone XS Max 的宽度,导致矩形(底部线)太宽,右边缘离开屏幕。同样,当我在 iPad 屏幕上进行测试时,底线太短了。而且,在任何设备上,旋转到横向视图都不会重新计算底线所需的矩形大小。

    我发现的最佳解决方案是将 CGRect 的宽度设置为大于最长的 iPad 尺寸(我随机选择 2000),然后添加 textfield.layer.masksToBounds = true。这完美工作了,因为现在这条线从一开始就很长,不需要重新计算,并且无论屏幕大小或方向如何,都被剪裁到 UITextField 的正确宽度。

    感谢 Mina,希望这可以帮助其他有同样问题的人!

    【讨论】:

    • 这是正确答案 + 解释,我希望接受的答案包含这个“陷阱”。我可以添加的一项改进是,您可以通过 UIScreen.main.bounds.width 使用实际的设备屏幕宽度,而不是选择任意宽度(而不是像接受的答案那样的文本字段的宽度!)。
    【解决方案4】:

    目标 C

    [txt.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
    [txt.layer setBorderColor: [[UIColor grayColor] CGColor]];
    [txt.layer setBorderWidth: 0.0];
    [txt.layer setCornerRadius:12.0f];
    [txt.layer setMasksToBounds:NO];
    [txt.layer setShadowRadius:2.0f];
    txt.layer.shadowColor = [[UIColor blackColor] CGColor];
    txt.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
    txt.layer.shadowOpacity = 1.0f;
    txt.layer.shadowRadius = 1.0f;
    

    斯威夫特

    textField.layer.backgroundColor = UIColor.whiteColor().CGColor
    textField.layer.borderColor = UIColor.grayColor().CGColor
    textField.layer.borderWidth = 0.0
    textField.layer.cornerRadius = 5
    textField.layer.masksToBounds = false
    textField.layer.shadowRadius = 2.0
    textField.layer.shadowColor = UIColor.blackColor().CGColor
    textField.layer.shadowOffset = CGSizeMake(1.0, 1.0)
    textField.layer.shadowOpacity = 1.0
    textField.layer.shadowRadius = 1.0
    

    【讨论】:

      【解决方案5】:

      我已经尝试了所有这些答案,但除了这个之外没有人为我工作

        let borderWidth:CGFloat = 2.0 // what ever border width do you prefer 
          let bottomLine = CALayer()
      
          bottomLine.frame = CGRectMake(0.0, Et_textfield.height  - borderWidth, Et_textfield.width, Et_textfield.height )
          bottomLine.backgroundColor = UIColor.blueColor().CGColor
          bottomLine
          Et_textfield.layer.addSublayer(bottomLine)
          Et_textfield.layer.masksToBounds = true // the most important line of code
      

      【讨论】:

        【解决方案6】:

        斯威夫特 3:

        只是子类你的 UITextField

        class BottomBorderTF: UITextField {
        
        var bottomBorder = UIView()
        override func awakeFromNib() {
        
            //MARK: Setup Bottom-Border
            self.translatesAutoresizingMaskIntoConstraints = false
            bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
            bottomBorder.backgroundColor = UIColor.orange
            bottomBorder.translatesAutoresizingMaskIntoConstraints = false
            addSubview(bottomBorder)
            //Mark: Setup Anchors
            bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
            bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
            bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
            bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength
        
           }
        }
        

        【讨论】:

        • 为什么不扩展?
        • 使用适合的方式。
        • 完美运行,只需将leftAnchor 更改为leadingAnchor 并将rightAnchor 更改为trailingAnchor
        【解决方案7】:

        使用 CALayer 的解决方案不好,因为当设备旋转时,下划线不会改变宽度。

        class UnderlinedTextField: UITextField {
        
            override func awakeFromNib() {
                super.awakeFromNib()
        
                let bottomLine = CALayer()
                bottomLine.frame = CGRect(x: 0, y: self.frame.size.height, width: UIScreen.main.bounds.width, height: 1)
                bottomLine.bounds = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: self.frame.size.height)
                bottomLine.backgroundColor = UIColor.black.cgColor
                borderStyle = .none
                layer.addSublayer(bottomLine)
                layer.masksToBounds = true
            }
        }
        

        最好的解决方案是使用 UIView。

        class UnderlinedTextField: UITextField {
            private let defaultUnderlineColor = UIColor.black
            private let bottomLine = UIView()
        
            override func awakeFromNib() {
                super.awakeFromNib()
        
                borderStyle = .none
                bottomLine.translatesAutoresizingMaskIntoConstraints = false
                bottomLine.backgroundColor = defaultUnderlineColor
        
                self.addSubview(bottomLine)
                bottomLine.topAnchor.constraint(equalTo: self.bottomAnchor, constant: 1).isActive = true
                bottomLine.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
                bottomLine.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
                bottomLine.heightAnchor.constraint(equalToConstant: 1).isActive = true
            }
        
            public func setUnderlineColor(color: UIColor = .red) {
                bottomLine.backgroundColor = color
            }
        
            public func setDefaultUnderlineColor() {
                bottomLine.backgroundColor = defaultUnderlineColor
            }
        }
        

        【讨论】:

          【解决方案8】:

          首先将borderStyle 属性设置为.none。

          另外,不要忘记在viewDidAppear(_:) 方法中调用此方法的最佳时间。

          为方便起见,您可以使用扩展程序:

          extension UIView {
              func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
                  let border = CALayer()
                  border.backgroundColor = color.cgColor
                  border.frame = CGRect(x: 0, y: self.frame.size.height - width, 
                                        width: self.frame.size.width, height: width)
                  self.layer.addSublayer(border)
              }
          }
          

          这样称呼:

          textfield.addBottomBorderWithColor(color: UIColor.lightGray, width: 0.5)
          

          【讨论】:

            【解决方案9】:

            对于那些正在寻找适用于 Autolayout、IBInspectable 和 Storyboard 的解决方案的人,请将 UITextField 子类化到您的自定义文本字段类中并添加以下内容:

            func setUnderline() {
                for sub in self.subviews {
                    sub.removeFromSuperview()
                }
                if underlineStyle == true {
                    var bottomBorder = UIView()
                    bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
                    bottomBorder.backgroundColor = borderColor  //YOUR UNDERLINE COLOR HERE
                    bottomBorder.translatesAutoresizingMaskIntoConstraints = false
                    self.addSubview(bottomBorder)
            
                    bottomBorder.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
                    bottomBorder.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
                    bottomBorder.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
                    bottomBorder.heightAnchor.constraint(equalToConstant: underlineHeight).isActive = true
                    layoutIfNeeded()
                }
            }
            
            @IBInspectable var underlineStyle: Bool = false {
                didSet {
                   setUnderline()
                }
            }
            
            @IBInspectable var underlineHeight: CGFloat = 0 {
                didSet {
                    setUnderline()
                }
            }
            

            【讨论】:

            • 这个。我在这里尝试了几乎所有其他方法,但在此之前,没有一种方法能很好地与我的混合自动布局方法配合使用:)
            【解决方案10】:

            斯威夫特 5.

            extension UITextField {
                let bottomLine = UIView()
                bottomLine.backgroundColor = .black
                borderStyle = .none
                    
                self.addSubview(bottomLine)
            
                NSLayoutConstraint.activate([
                    bottomLine.topAnchor.constraint(equalTo: bottomAnchor + 10),
                    bottomLine.leadingAnchor.constraint(equalTo: leadingAnchor),
                    bottomLine.trailingAnchor.constraint(equalTo: trailingAnchor),
                    bottomLine.heightAnchor.constraint(equalToConstant: 1)
                ]) 
            }
            

            【讨论】:

              【解决方案11】:

              对于多个文本字段

                override func viewDidLoad() {
              
              
                  configureTextField(x: 0, y: locationField.frame.size.height-1.0, width: locationField.frame.size.width, height:1.0, textField: locationField)
                  configureTextField(x: 0, y: destinationField.frame.size.height-1.0, width: destinationField.frame.size.width, height:1.0, textField: destinationField)
                  configureTextField(x: 0, y: originField.frame.size.height-1.0, width: originField.frame.size.width, height:1.0, textField: originField)
                  configureTextField(x: 0, y: nameField.frame.size.height-1.0, width: nameField.frame.size.width, height:1.0, textField: nameField)
              
                  locationField.text="Hello"
                  super.viewDidLoad()
              
                  // Do any additional setup after loading the view.
              }
              
              func configureTextField(x:CGFloat,y:CGFloat,width:CGFloat,height:CGFloat,textField:UITextField)
              
              {
                  let bottomLine = CALayer()
                  bottomLine.frame = CGRect(x: x, y: y, width: width, height: height)
                  bottomLine.backgroundColor = UIColor.white.cgColor
                  textField.borderStyle = UITextBorderStyle.none
                  textField.layer.addSublayer(bottomLine)
              
              
              }
              

              【讨论】:

                【解决方案12】:

                Textfield 底部边框设置,但设备存在更多问题。因此底部边框不适合 textfield。我检索该问题的代码是这样的 它工作正常 迅捷4.2

                let bottomLine = CALayer()
                        bottomLine.frame = CGRect(x: 0.0, y: textField.frame.height - 1, width: screenSize.width - 32, height: 1.0)
                        bottomLine.backgroundColor = UIColor(hex: 0xD5D5D5).cgColor
                        textField.borderStyle = UITextField.BorderStyle.none
                        textField.layer.addSublayer(bottomLine)
                

                【讨论】:

                  【解决方案13】:

                  对于 swift 4。这对我有用。

                     let myfield:UITextField = {
                          let mf=UITextField()
                          let atributePlaceHolder=NSAttributedString(string: "Text_description", attributes:[NSAttributedString.Key.foregroundColor :UIColor.darkGray])
                          mf.textColor = .gray
                          mf.attributedPlaceholder=atributePlaceHolder
                          mf.layer.borderColor = UIColor.black.cgColor
                          mf.layer.backgroundColor = UIColor.white.cgColor
                          mf.layer.borderWidth = 0.0
                          mf.layer.shadowOffset = CGSize(width: 0, height: 1.0)
                          mf.layer.shadowOpacity = 1.0
                          mf.layer.shadowRadius = 0.0
                          return mf
                      }()
                  

                  【讨论】:

                    【解决方案14】:

                    使用扩展和 Swift 5.3

                    extension UITextField {
                        internal func addBottomBorder(height: CGFloat = 1.0, color: UIColor = .black) {
                            let borderView = UIView()
                            borderView.backgroundColor = color
                            borderView.translatesAutoresizingMaskIntoConstraints = false
                            addSubview(borderView)
                            NSLayoutConstraint.activate(
                                [
                                    borderView.leadingAnchor.constraint(equalTo: leadingAnchor),
                                    borderView.trailingAnchor.constraint(equalTo: trailingAnchor),
                                    borderView.bottomAnchor.constraint(equalTo: bottomAnchor),
                                    borderView.heightAnchor.constraint(equalToConstant: height)
                                ]
                            )
                        }
                    }
                    

                    【讨论】:

                    • 这对我来说是更好的解决方案,因为我需要隐藏/显示 TextField 并且不能使用框架和 CALayer,因为我必须在 viewDidLoad 中这样做。
                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2022-11-18
                    • 2020-05-10
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多