I am creating a pulldown menu using a stackview in conjunction with a textfield. When the textfield is tapped, I animate the contents of the stackview by "growing" the stackview upwards, but it is doing it from the bottom-left to the top-right corner. How can I make it "grow" straight up vertically upwards? I suspect that it may be due to the width of the buttons not being equal to the width of the stackview, but I have already set the stackview's alignment property to .fill as well as set a constraint to make the stackview's width anchor equal to the textfield's width anchor. So, I am not sure what I need to fix. Here's the code followed by a clip of how it looks right now.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textfield: UITextField!
@IBOutlet weak var label: UILabel!
var popup: UIStackView = {
let selectionList = ["Apple",
"Grapefriut",
"Peach",
"Orange",
"Pear ",
]
let pop = UIStackView()
pop.axis = .vertical
pop.spacing = 0
pop.distribution = .fillEqually
pop.alignment = .fill
pop.layer.borderWidth = 1
pop.layer.borderColor = UIColor.darkGray.cgColor
pop.layer.cornerRadius = 6
pop.clipsToBounds = true
for selection in selectionList {
let button = UIButton()
button.setTitle(selection, for: .normal)
button.backgroundColor = #colorLiteral(red: 0.8202667832, green: 0.9491913915, blue: 1, alpha: 1)
button.setTitleColor(.darkGray, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
button.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside)
button.isHidden = true
pop.addArrangedSubview(button)
}
return pop
}()
override func viewDidLoad() {
super.viewDidLoad()
textfield.delegate = self
let imageView = UIImageView(image: UIImage(named: "downarrow20x20"))
imageView.contentMode = .center
imageView.frame = CGRect(x: 0, y: 0, width: imageView.image!.size.width + 20.0, height: imageView.image!.size.height)
textfield.rightView = imageView
textfield.rightViewMode = .always
textfield.inputView = UIView() // disable keyboard from popping up
view.addSubview(popup)
popup.translatesAutoresizingMaskIntoConstraints = false
popup.bottomAnchor.constraint(equalTo: textfield.bottomAnchor).isActive = true
popup.widthAnchor.constraint(equalTo: textfield.widthAnchor).isActive = true
popup.centerXAnchor.constraint(equalTo: textfield.centerXAnchor).isActive = true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
showHidePopupContents(hide: false)
}
private func showHidePopupContents(hide: Bool) {
UIView.animate(withDuration: 0.3) {
self.popup.subviews.forEach { btn in
btn.isHidden = hide
}
}
}
@objc func selectionTapped(_ button: UIButton) {
if let buttonStr = button.title(for: .normal) {
let str = buttonStr.trimmingCharacters(in: .whitespacesAndNewlines)
label.text = "\(str) selected"
textfield.text = str
}
// get focus out of textfield
textfield.isEnabled = false
textfield.isEnabled = true
showHidePopupContents(hide: true)
}
}