Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

前端 未结 22 2306
自闭症患者
自闭症患者 2020-11-27 09:19

I would like to keep the border at the bottom part only in UITextField. But I don\'t know how we can keep it on the bottom side.

Can you please advise m

22条回答
  •  無奈伤痛
    2020-11-27 09:55

    If you want to do without knowing frames beforehand, without subclassing and without Autolayout:

    Swift 5 / Swift 4.x / Swift 3.x

    extension UITextField {
      func setBottomBorder() {
        self.borderStyle = .none
        self.layer.backgroundColor = UIColor.white.cgColor
    
        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
      }
    }
    

    Call as yourTextField.setBottomBorder() from anywhere without making sure of the frames to be right.

    The Result looks like this:

    Swift UI

    struct MyTextField: View {
      var myPlaceHolder: String
      @Binding var text: String
    
      var underColor: Color
      var height: CGFloat
    
      var body: some View {
        VStack {
            TextField(self.myPlaceHolder, text: $text)
            .padding()
            .font(.title)
    
            Rectangle().frame(height: self.height)
                .padding(.horizontal, 24).foregroundColor(self.underColor)
        }
      }
    }
    

提交回复
热议问题