简体   繁体   中英

UITextField change width when clicking button

I want to make a search field in my app, and I was wondering if it is possible to make it invisible to begin with and then make it appear with the click of a button, like with the magnifying glass in the video below.

在此处输入图像描述

I have tried making the width of a UITextField 0 to begin with and then make a button make the width larger, but I am doing something wrong, and I can not figure out what. Maybe you could make an example in a blank project and show/link the code?

I hope you can help:)

UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
        //change view width
    }) { (completed) in
        //you can use completion or you can delete I am using it like that
        self.searchTextview.becomeFirstResponder()
    }

I am using this for my view. You can change for your need. Change constraints or width with animation

Function for expand the SearchTextField

  func setTextField(setExpand:Bool = false){

        self.txtfldSearch.delegate = self
        self.txtfldSearch.borderStyle = UITextField.BorderStyle.none
        self.txtfldSearch.translatesAutoresizingMaskIntoConstraints = true
        let bottomLine = CALayer()
        bottomLine.backgroundColor = UIColor.red.cgColor
        UIView.animate(withDuration: 0.5) {
          if setExpand{
                      self.txtfldSearch.frame = CGRect(x: 
                      self.viewContainer.frame.origin.x + 8, y: 
                      self.txtfldSearch.frame.origin.y, width: 
                      (self.btnSearch.frame.origin.x - 
                      (self.viewContainer.frame.origin.x + 16)), 
                       height: self.txtfldSearch.frame.size.height)
                       bottomLine.frame = CGRect(x: 0.0, y: 
                      self.txtfldSearch.frame.size.height-2, width: 
                      self.txtfldSearch.frame.size.width, height: 2.0)
            }
       else{
                    self.txtfldSearch.frame = CGRect(x: 
                    self.btnSearch.frame.origin.x - 8, 
                    y: self.txtfldSearch.frame.origin.y, width: 0, 
                    height:self.txtfldSearch.frame.size.height)
                    bottomLine.frame = CGRect(x: 0.0, y: 
                    self.txtfldSearch.frame.size.height-2, width: 
                    self.txtfldSearch.frame.size.width, height: 2.0)
            }  
      }    
    self.txtfldSearch.layer.addSublayer(bottomLine)

}

Use of Code For Expanding pass true and other case pass false

  self.setTextField(setExpand: true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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