使用Swift只使用底部边框使输入框透明

3

如何创建一个带透明背景并且只有下边框的文本框?

我尝试过以下代码:

textField.backgroundColor = .clear
let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGrayColor().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

但是它没有起作用。

定义“isn't working”。 - rmaddy
@rmaddy 它只是显示一个空白的空间。 - user7444742
使用约束的Xib-只需在文本编辑框下方创建一个高度为1行的框。不使用约束的Xib-执行相同操作,但将重设掩模与文本字段相同。这些都不需要任何代码,即使采用M Dan的答案也是如此。我建议阅读苹果公司的4个指南:视图、视图控制器、动画、Quartz2D。 - Stephen J
6个回答

6
这里提供另一种使用UIView而非CALayer的实现方式。
let line = UIView()
line.frame.size = CGSize(width: textField.frame.size.width, height: 1)
line.frame.origin = CGPoint(x: 0, y: textField.frame.maxY - line.frame.height)
line.backgroundColor = UIColor.darkGray
line.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
textField.addSubview(line)

你很聪明。你非常聪明。 - user7444742

3

您的代码是正确的。问题仅在于您的边框高度,现在是“textField.frame.size.height”,请将其更改为1.0(更改边框框架代码)。


请注意,UIRectEdge类型是一个OptionSet(它可能有多个边缘),因此在切换其情况时,您需要将其与仅包含单个元素的Set进行比较。只有在默认情况下(且仅在默认情况为空时)才需要使用break。 - Leo Dabus

2
请尝试这个:
txtField .borderStyle = .none

它可能会帮助你....:)


1
extension UITextField {
    func setBottomBorder(borderColor: CGColor = UIColor.white.cgColor,
        backgroundColor: CGColor = UIColor.clear.cgColor) {
        self.borderStyle = .none
        self.layer.backgroundColor = backgroundColor

        let border = CALayer()
        let width = CGFloat(2.0)
        border.borderColor = borderColor
        border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)
        border.borderWidth = width
        self.layer.addSublayer(border)
        self.layer.masksToBounds = true
    }
}

这对我有用。

然后你可以直接调用

yourTextField.SetBottomBorder(borderColor: UIColor.white.cgColor, backgroundColor: UIColor.clear.cgColor)

0

这段代码对我来说似乎运行良好,将backgroundColor设置为clear可以解决这个问题

textField.backgroundColor = .clear


0
只需在您的代码中添加这行即可:-
   border.backgroundColor = UIColor.black.cgColor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接