UITextField Only Top And Bottom Border

后端 未结 11 996
温柔的废话
温柔的废话 2020-12-07 22:46

I currently have a regular border. I would like to only have a top and bottom border.

How do I accomplish this?

Using the UITextField<

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 23:52

    @Sebyffffd why stop there? (;

    EDIT: There is an issue with lines being drawn before auto layout sets the right frame for the view, I edited my answer with a fix: it basically involves calling drawLines() in layoutSubviews():

    class FramedTextField: UITextField {
    
        @IBInspectable var linesWidth: CGFloat = 1.0 { didSet{ drawLines() } }
    
        @IBInspectable var linesColor: UIColor = UIColor.blackColor() { didSet{ drawLines() } }
    
        @IBInspectable var leftLine: Bool = false { didSet{ drawLines() } }
        @IBInspectable var rightLine: Bool = false { didSet{ drawLines() } }
        @IBInspectable var bottomLine: Bool = false { didSet{ drawLines() } }
        @IBInspectable var topLine: Bool = false { didSet{ drawLines() } }
    
    
    
        func drawLines() {
    
            if bottomLine {
                add(CGRectMake(0.0, frame.size.height - linesWidth, frame.size.width, linesWidth))
            }
    
            if topLine {
                add(CGRectMake(0.0, 0.0, frame.size.width, linesWidth))
            }
    
            if rightLine {
                add(CGRectMake(frame.size.width - linesWidth, 0.0, linesWidth, frame.size.height))
            }
    
            if leftLine {
                add(CGRectMake(0.0, 0.0, linesWidth, frame.size.height))
            }
    
        }
    
        typealias Line = CGRect
        private func add(line: Line) {
            let border = CALayer()
            border.frame = line
            border.backgroundColor = linesColor.CGColor
            layer.addSublayer(border)
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            drawLines()
        }
    
    }
    

提交回复
热议问题