使用UITextField + UIPickerview时禁用键盘输入

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用UITextField + UIPickerview时禁用键盘输入相关的知识,希望对你有一定的参考价值。

此项目还会单击文本字段选择器视图打开,但上面显示的数据可以在该部分中输入。我怎么能把它关掉?所以请在下面做出我的选择。

如果单击文本字段,则打开uipickerview:

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()
    }


}
答案

您可以实现UITextFieldDelegate方法:

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

返回false以防止手动输入任何字符。

另一答案

在真正的iPhone设备上运行时,这不是一个实际问题,因为没有键盘可用于输入:)

这在ios模拟器上运行时似乎只是一个问题,因为您也可以使用Mac键盘。


话虽如此,如果您仍想阻止文本输入到您的字段,您肯定应该使用Mr. Hedgehog answer

如果除了阻止输入之外,您可能还想隐藏文本字段上的插入符号,请尝试以下操作:

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

如果你想阻止用户使用paste动作,你可以创建一个UITextField的子类来覆盖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)
    }
}

这是一个doc列表的行动。

以上是关于使用UITextField + UIPickerview时禁用键盘输入的主要内容,如果未能解决你的问题,请参考以下文章

如何测试 DatePickerIOS

使用 addSubview 动态添加 UITextField 的 UITableViewCell - 如何在键盘上“返回”时获取 UITextField 值

在 iOS 中使用 UITextField 条目作为数组

使用 UITableView 而不是 UIPickerView 来设置 UITextField 文本

在 UITextField 上使用“下一个”版本的 Return 按钮移动到下一个 UITextField 的最佳方式

如何更好地识别 UITextField