简体   繁体   English

如何通过swift将底线添加到子视图中的多个UITextField?

[英]How to add bottom line to multiple UITextField in subviews by swift?

I need to add bottom line to all of my textfield in my subview. 我需要在子视图中向所有文本字段添加底线。

This is my code. 这是我的代码。

for view in self.detailView.subviews as! [UIView] {
        if let textField = view as? UITextField {
            //                if textField.text == "" {
            //                    // show error
            //                    return
            //                }

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

            border.borderWidth = width

            textField.layer.addSublayer(border)
            textField.layer.masksToBounds = true

            return
        }
    }

But it only add bottom line to the last textfield not all of it. 但它只会将底线添加到最后一个文本字段,而不是全部。 This is What i got 这就是我得到的

在此处输入图片说明

How can i fix this? 我怎样才能解决这个问题? Thanks! 谢谢!

You have added return keyword at end. 您已在最后添加return关键字。

Try to loop whole view with its subviews like as 尝试将整个视图及其子视图循环为

for view in self.view.subviews as! [UIView] {
            if let textField = view as? UITextField {
                var border = CALayer()
                var width = CGFloat(1.0)
                border.borderColor = UIColor.whiteColor().CGColor
                border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width:  textField.frame.size.width, height: width)

                border.borderWidth = width
                textField.borderStyle = UITextBorderStyle.None
                textField.layer.addSublayer(border)
                textField.layer.masksToBounds = true
            }
        }

I have added one more line of code textField.borderStyle = UITextBorderStyle.None so that if the border style is different in design then it will change by programmatically. 我又添加了一行代码,代码为textField.borderStyle = UITextBorderStyle.None因此,如果边框样式在设计上有所不同,则它将以编程方式进行更改。

Very simple and easy method Just put background image of textfield This image have a white background and underline so you use transparent background instead white background 非常简单易用的方法只需将文本字段的背景图像放置在白色背景上并带有下划线,以便使用透明背景代替白色背景

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM