Disabling keyboard input when using a UITextField + UIPickerview

扶醉桌前 提交于 2019-12-02 08:36:37

问题


This project also click on the textfield pickerview opens, but the data shown above can be entered in the section. How can I turn it off? So just come to my choices below.

If the textfield is clicked, I open the pickerview:

import UIKit
import NVActivityIndicatorView

struct kategoriData {
    var text : String?
    var id : String?
}

class KonuEkleViewController: UIViewController,UITextFieldDelegate , NVActivityIndicatorViewable , UIPickerViewDataSource , UIPickerViewDelegate{
    @IBOutlet weak var txtBaslik: UITextField!
    @IBOutlet weak var txtYazi: UITextView!
    @IBOutlet weak var txtLink: UITextField!
    @IBOutlet weak var btnKonuAc: UIButton!
    @IBOutlet weak var txtKategoriSecimi: UITextField!

    let size = CGSize(width: 30, height: 30)
    let singleton = Global.sharedGlobal
    let ConnectString = Connect.ConnectInfo
    var kategoriList = [kategoriData]()
    let GirisView = GirisViewController()
    var secilenKategori : String?

    var dbKategoriIsim : String?
    var dbKategoriId:String?

    override func viewDidLoad() {
        super.viewDidLoad()
        txtKategoriSecimi.text = "Kategoriyi Seçiniz"
        KategoriGetir()
        pickerGrafik()
        txtYazi.layer.cornerRadius = 10
        btnKonuAc.layer.cornerRadius = 10

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(GirisViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)
    }
    func dismissKeyboard() {
        view.endEditing(true)
    }


    @IBAction func btnKonuEkle(_ sender: Any) {
       GirisView.LoadingIcon(tur: 0)
        if txtBaslik.text != "" && txtYazi.text != "" && secilenKategori != nil && txtKategoriSecimi.text != "Kategoriyi Seçiniz"
        {
            KonuEkle(uye: singleton.username, baslik: txtBaslik.text!, mesaj: txtYazi.text, kategori: secilenKategori!, link: txtLink.text!)
        }
        else
        {
            GirisView.Bildiri(baslik: "UYARI", mesaj: "Boş Alanları Doldurunuz", tur: 1)
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
            self.GirisView.LoadingIcon(tur: 1)
        }

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
    func KonuEkle(uye:String , baslik:String ,mesaj:String , kategori:String , link:String)
    {
        var request = URLRequest(url: URL(string:ConnectString.conString + "/KonuEkle")!)
        request.httpMethod = "POST"
        var postString = "uye="+uye+"&&baslik="+baslik+"&&mesaj="+mesaj+"&&kategori="+kategori+"&&link="+link
        postString = postString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            if error != nil
            {
                print("error")
            }

            if let urlContent = data
            {

                do
                {
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(jsonResult)
                    if let gelenDizi = jsonResult as? NSArray
                    {
                        for i in 0..<gelenDizi.count
                        {
                            if let gelenMesaj = (gelenDizi[i] as? NSDictionary)?["mesaj"] as? String
                            {
                                DispatchQueue.main.async {
                                    self.Sonuc(mesaj:gelenMesaj)
                                }

                            }

                        }

                    }


                }
                catch
                {
                    print("server hatası")
                }
            }
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
                self.GirisView.LoadingIcon(tur: 1)
            }
        }
        task.resume()
    }


    func Sonuc(mesaj:String)
    {
        var mesajSonuc = ""
        var mesajBaslik = ""

        if mesaj == "basarili"
        {
            mesajSonuc = "Konu Açıldı"
            mesajBaslik = "Bilgi"
        }
        else
        {
            mesajSonuc = "Bir Hata Oluştu Lütfen Destek Bölümünden Bize Ulaşın"
            mesajBaslik = "Uyarı"
        }

        let appearance = SCLAlertView.SCLAppearance(showCloseButton: false)
        let alert = SCLAlertView(appearance: appearance)
        _ = alert.addButton("Tamam") {

            self.txtLink.text = ""
            self.txtYazi.text = ""
            self.txtBaslik.text = ""
            self.navigationController!.popViewController(animated: true)
        }
        if mesajBaslik == "Bilgi"
        {
        _ = alert.showSuccess(mesajBaslik, subTitle:mesajSonuc)
        }
        else
        {
        _ = alert.showNotice(mesajBaslik, subTitle:mesajSonuc)
        }

    }
        func pickerGrafik()
    {
        let pickerView = UIPickerView()

        pickerView.delegate = self

        txtKategoriSecimi.inputView = pickerView

        let toolBar = UIToolbar(frame: CGRect(x: 0, y: self.view.frame.size.height/6, width: self.view.frame.size.width, height: 40.0))

        toolBar.layer.position = CGPoint(x: self.view.frame.size.width/2, y: self.view.frame.size.height-20.0)

        toolBar.barStyle = UIBarStyle.blackTranslucent

        toolBar.tintColor = UIColor.white

        toolBar.backgroundColor = UIColor.black


        let defaultButton = UIBarButtonItem(title: "İptal", style: UIBarButtonItemStyle.plain, target: self, action: #selector(KonuEkleViewController.tappedToolBarBtn))

        let doneButton = UIBarButtonItem(title: "Tamam", style: UIBarButtonItemStyle.done, target: self, action: #selector(KonuEkleViewController.donePressed))

        let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)

        let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width / 3, height: self.view.frame.size.height))

        label.font = UIFont(name: "Helvetica", size: 12)

        label.backgroundColor = UIColor.clear

        label.textColor = UIColor.white

        label.text = "Kategoriyi Seçiniz"

        label.textAlignment = NSTextAlignment.center

        let textBtn = UIBarButtonItem(customView: label)

        toolBar.setItems([defaultButton,flexSpace,textBtn,flexSpace,doneButton], animated: true)

        txtKategoriSecimi.inputAccessoryView = toolBar
    }

    func donePressed(_ sender: UIBarButtonItem) {
        txtKategoriSecimi.resignFirstResponder()
    }

    func tappedToolBarBtn(_ sender: UIBarButtonItem) {

        txtKategoriSecimi.resignFirstResponder()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return kategoriList.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return kategoriList[row].text
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        txtKategoriSecimi.text = kategoriList[row].text
        secilenKategori = kategoriList[row].id
    }

    func KategoriGetir()
    {
        kategoriList.removeAll()
        //SADECE 1 DEFA EKLENIYOR
        self.kategoriList.append(kategoriData.init(text: "Kategoriyi Seçiniz", id: "1"))
        GirisView.LoadingIcon(tur: 0)
        var request = URLRequest(url: URL(string:ConnectString.conString + "/KategoriGetir")!)
        request.httpMethod = "POST"
        var postString = "tur=1&&kategori="
        postString = postString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            if error != nil
            {
                print("error")
            }

            if let urlContent = data
            {
                do
                {
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(jsonResult)
                    if let gelenDizi = jsonResult as? NSArray
                    {
                        for i in 0..<gelenDizi.count
                        {

                            if let gelenKategori = (gelenDizi[i] as? NSDictionary)?["kategoriisim"] as? String
                            {
                                self.dbKategoriIsim = gelenKategori
                            }
                            if let gelenId = (gelenDizi[i] as? NSDictionary)?["id"] as? String
                            {
                                self.dbKategoriId = gelenId
                            }
                            self.kategoriList.append(kategoriData.init(text: self.dbKategoriIsim, id: self.dbKategoriId))

                        }

                    }



                }
                catch
                {
                    print("error")
                }
            }
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
                self.GirisView.LoadingIcon(tur: 1)
            }
        }
        task.resume()
    }


}

回答1:


You can implement the UITextFieldDelegate method:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

To return false so that entering any character by hand would be prevented.




回答2:


This isn't an actual problem when running on a real iPhone device, since no keyboard will be available to do the typing :)

This is only seems like an issue when running on the iOS simulator, since you can then use your Mac keyboard as well.


Having said, you definitely should go with Mr. Hedgehog answer if you still want to block text input to your field.

If, besides blocking input, you may also want to hide the caret on the text field, also try this:

class PickerBasedTextField: UITextField {
    override func caretRect(for position: UITextPosition) -> CGRect {
        return CGRect.zero
    }
}



回答3:


If you want to prevent user from using paste action, you can make a subclass of UITextField to override canPerformAction.

public class PickerUITextField: UITextField {
    override public func canPerformAction(_ action: Selector, withSender 
                                            sender: Any?) -> Bool {
        if action == #selector(UIResponderStandardEditActions.paste(_:)) {
            return false
        }
        return super.canPerformAction(action, withSender: sender)
    }
}

Here is a doc for list of actions.



来源:https://stackoverflow.com/questions/43688210/disabling-keyboard-input-when-using-a-uitextfield-uipickerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!