iosswiftuitoolbaruitapgesturerecognizer

Show toolbar when image is tapped SWIFT


I have an textfield with icon :

I can show toolBar when user tap on textfield. But I need to do same thing with icon. I try to do with gesture rezognizer but I can't show toolBar. What is the problem ?

func createToolbar() {
        
        toolBar.sizeToFit()
    
        let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let tamamButton = UIBarButtonItem(title: NSLocalizedString("done", comment: ""), style: .plain, target: self, action: #selector(loadNewPriceAndReload))
        
        toolBar.setItems([spaceButton,tamamButton], animated: false)
        
        toolBar.isUserInteractionEnabled = true
        pickerTextField.inputAccessoryView = toolBar
        
    }

 func createPickerView() {
        
        
        pickerView.delegate = self
        pickerView.dataSource = self
        pickerView.backgroundColor = #colorLiteral(red: 0.1834549492, green: 0.1834549492, blue: 0.1834549492, alpha: 1)
        pickerView.tintColor = .white
        
        pickerTextField.inputView = pickerView
        
        
    }

I try to call functions when I tapped icon but it doesn't work.

This is extension to put icon on right side to the textField

extension UITextField {
    func setIcon(_ image: UIImage,tap:UIGestureRecognizer) {
   let iconView = UIImageView(frame:
                  CGRect(x: 7, y: 11, width: 15, height: 10))
    iconView.image = image
       
    
        iconView.isUserInteractionEnabled = true
         
        iconView.addGestureRecognizer(tap)
    
        
    let iconContainerView: UIView = UIView(frame:
                  CGRect(x: -50, y: 0, width: 30, height: 32))
    
        
        
    iconContainerView.layer.cornerRadius = 3
    iconContainerView.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]
    
    iconContainerView.addSubview(iconView)
    iconContainerView.backgroundColor = #colorLiteral(red: 0.04554035515, green: 0.5175096393, blue: 0.7420636415, alpha: 1)
    
   rightView = iconContainerView
   rightViewMode = .always
}
    
}

enter image description here


Solution

  • To show the pickerView whether due to textField or any other, i always tend to go with this approach:

     let picker = UIPickerView()
     picker.translatesAutoresizingMaskIntoConstraints = false
     view.addSubview(picker)
    
     picker.leadingAnchor.constraint(equalTo:   view.safeAreaLayoutGuide.leadingAnchor).isActive = true
     picker.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
     picker.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true