how to make designable textfield code class in swift

后端 未结 1 1486
旧时难觅i
旧时难觅i 2021-01-07 11:54

I am a beginner in programming and in iOS development. I want to make a swift file that contains a code to make Designable textfield, so I will not edit the UI element displ

相关标签:
1条回答
  • 2021-01-07 12:18

    There are two solutions for this

    The First solution is the easiest one. You can have a view and insert inside the view a UIImageView, UITextField, UIImageView. Add constraints to set the desired sizes. You can make the text field transparent. With this method, you can customize it how you want.

    The Second solution is how you are doing it.

    The first thing you need to do is add the properties to the right image and right padding. Under the left padding property add the following code:

     @IBInspectable var rightImage : UIImage? {
        didSet {
          updateRightView()
        }
      }
    
      @IBInspectable var rightPadding : CGFloat = 0 {
        didSet {
          updateRightView()
        }
      }
    

    With this new properties, you can choose the image and edit the x location.

    After the update function create a new function called updateRigthView

    Like this:

        func updateRightView() {
        if let image = rightImage {
          rightViewMode = .always
    
          // assigning image
          let imageView = UIImageView(frame: CGRect(x: rightPadding, y: 0, width: 20, height: 20))
          imageView.image = image
    
          var width = rightPadding - 20
    
          if borderStyle == UITextBorderStyle.none || borderStyle == UITextBorderStyle.line {
            width -= 5
          }
    
          let view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 20)) // has 5 point higher in width in imageView
          view.addSubview(imageView)
    
    
          rightView = view
    
        } else {
          // image is nill
          rightViewMode = .never
        }
      }
    

    You had to edit the right properties.Now head to storyboard and try it out. To move the image to the left decrease the right padding 0,-1,-2,-3, etc. To move the image to the right increase the right padding 0,1,2,3.

    0 讨论(0)
提交回复
热议问题