John Doah
John Doah

Reputation: 1999

Trying to animate UITextfield width constraint, but it won't work

I'm trying to animate a width constraint of a UITextfield I have, what I'm trying to achieve is to get the UITextfield from width 0 to width X while animating.

This is what I have so far:

let MAX_SEARCH_BAR_WIDHT: CGFloat = 285
var searchBarWidth: CGFloat = 0

private func setupSearchBar()  {
    addSubview(searchBar)
    NSLayoutConstraint.activate([
        searchBar.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 8),
        searchBar.trailingAnchor.constraint(equalTo: searchBtn.leadingAnchor, constant: -8),
        searchBar.heightAnchor.constraint(equalToConstant: 30),
        searchBar.widthAnchor.constraint(equalToConstant: searchBarWidth),
    ])
}

This is where I'm trying to animate the UITextfield:

func handleSearch() {
    mView.isSearchingAlready = !mView.isSearchingAlready
    UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
        self.mView.searchBarWidth += self.mView.MAX_SEARCH_BAR_WIDHT
        self.mView.layoutIfNeeded()
    }, completion: nil)
}

handleSearch is called when I'm tapping a search button. when clicking the button, the UITextfield won't show up. This is the UITextfield:

let searchBar: UITextField = {
   let field = UITextField(frame: CGRect(x: 0, y: 0, width: 1, height: 0))
    field.backgroundColor = .appWhite
    field.tintColor = UIColor.clear
    field.translatesAutoresizingMaskIntoConstraints = false
    field.layer.cornerRadius = 15
    field.isHidden = false

    let padding = UIView(frame: CGRect(x: 0, y: 0, width: 8, height: 1))
    field.leftView = padding
    field.leftViewMode = .always
    field.rightView = padding
    field.rightViewMode = .always

    field.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("searchbar.placeholder", comment: "find"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.init(hexString: "#080708", alpha: 0.5)])

    return field
}()

Upvotes: 1

Views: 96

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You should change the constraint's constant value , so create a var

var widthCon:NSLayoutConstraint! 

Get the width constraint out of the activate block

widthCon = searchBar.widthAnchor.constraint(equalToConstant: searchBarWidth)
widthCon.isActive = true

Then

func handleSearch() {
    mView.isSearchingAlready = !mView.isSearchingAlready
    self.mView.widthcon.constant = self.mView.MAX_SEARCH_BAR_WIDHT
    UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: { 
        self.view.layoutIfNeeded()
    }, completion: nil)
}

Upvotes: 1

Related Questions