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

Posted

技术标签:

【中文标题】使用 UITextField + UIPickerview 时禁用键盘输入【英文标题】:Disabling keyboard input when using a UITextField + UIPickerview 【发布时间】:2017-04-28 20:12:24 【问题描述】:

这个项目同样点击textfield pickerview打开,但是上面显示的数据可以在section中输入。我怎样才能关闭它?因此,请在下面进行我的选择。

如果文本框被点击,我打开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】:

你可以实现UITextFieldDelegate方法:

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

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

【讨论】:

好答案,应该可以解决问题!请在下面查看我的答案以获取更多考虑。快乐的黑客攻击! 如果您还在寻找修复该空白插入符的方法,这里是另一个修复该问题的 SO***.com/questions/39503873/…【参考方案2】:

这不是真正的问题在真正的 iPhone 设备上运行时,因为没有可用的键盘来进行打字:)

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


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

如果除了阻止输入之外,您可能还想隐藏文本字段上的插入符号,也可以试试这个:

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

【讨论】:

【参考方案3】:

如果您想阻止用户使用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 时禁用键盘输入的主要内容,如果未能解决你的问题,请参考以下文章

UIPicker 作为 UITextfield 键盘的输入

如何为 iOS 7 创建弹出式 uipicker 和 uitextfield?

将 UITextField 的 inputView 属性设置为 UIPicker 在 Swift 中不起作用

UITextField 上的下拉菜单?

自动向下滚动到下一个 UITextField

如何关闭操作表