代码之家  ›  专栏  ›  技术社区  ›  TheRedCamaro3.0 3.0

UITextField键盘在每次按键后关闭

  •  0
  • TheRedCamaro3.0 3.0  · 技术社区  · 8 年前

    我看过其他的答案,到目前为止没有一个是有用的。“我的UITextField”的键盘在每次按键后都会折叠。我不确定是什么原因造成的。我有一个扩展,在显示键盘时发出警报,但在我创建的其他项目中也可以使用。

    下面是完整的代码

    import UIKit
    
    class ViewController: UIViewController,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,UICollectionViewDataSource,printDelegateWorkedDelegate{
    
    
        func printDelegateWorkedDelegate() {
            print("The delegate worked")
        }
    
        var genericTagsArray:[String] = ["tag1","tag2","tag3","tag4","tag5","tag6","tag7","tag8","tag9","tag10","tag11","tag12","A","B","C","D","E","F","G","Ab","Abc","za","tag1","tag2","tag3","tag4","tag5","tag6","tag7","tag8","tag9","tag10","tag11","tag12","A","B","C","D","E","F","G","Ab","Abc","za"]
        var currentTagsArray:[String] = [String]()
        var tagsSelected:[String] = [String]()
        let keyboardSlider = KeyboardSlider()
    
        var header:feedViewHeader = feedViewHeader()
    
        @IBOutlet weak var feedScreenCollectionView: UICollectionView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            keyboardSlider.subscribeToKeyboardNotifications(view: view)
            currentTagsArray = genericTagsArray
    
            let viewTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(feedViewHeader.viewTapped(gestureRecognizer:)))
            viewTapGestureRecognizer.cancelsTouchesInView = false
            self.feedScreenCollectionView.addGestureRecognizer(viewTapGestureRecognizer)
    
            feedScreenCollectionView.delegate = self
            feedScreenCollectionView.dataSource = self
    
            let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
            layout.sectionInset = UIEdgeInsets(top: 5, left: 1, bottom: 0, right: 1)
            layout.minimumLineSpacing = 0
            layout.headerReferenceSize = CGSize(width: 50, height: 75)
    
            layout.sectionHeadersPinToVisibleBounds = true
            feedScreenCollectionView.collectionViewLayout = layout
        }
    
    
        func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
            header.VC = self
            header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "feedViewHeader", for: indexPath) as! feedViewHeader
    
            return header
        }
    
        func numberOfSections(in collectionView: UICollectionView) -> Int {
            return 1
        }
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return currentTagsArray.count
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "feedViewCell", for: indexPath) as! feedViewCell
    
            cell.feedImageView.backgroundColor = .blue
            cell.feedImageView.clipsToBounds = true
            cell.feedImageView.layer.cornerRadius = CGFloat((cell.feedImageView.frame.width)/5)
            cell.feedLabel.text = currentTagsArray[indexPath.item]
            return cell
        }
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
            return 0
        }
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
            return 0
        }
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
            let collectionViewWidth = collectionView.bounds.width/4.0
            let collectionViewHeight = collectionViewWidth
    
            return CGSize(width: collectionViewWidth-4, height: collectionViewHeight+25)
        }
    
        var lastContentOffset:CGFloat = 0
    
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
    
            if self.lastContentOffset > self.feedScreenCollectionView.contentOffset.y && self.feedScreenCollectionView.contentOffset.y > 0 && self.feedScreenCollectionView.contentOffset.y < self.feedScreenCollectionView.frame.maxY {
                self.lastContentOffset = scrollView.contentOffset.y
                header.isHidden = false
            }
            else if (self.lastContentOffset < self.feedScreenCollectionView.contentOffset.y) && (self.feedScreenCollectionView.contentOffset.y < self.feedScreenCollectionView.frame.maxY) && (self.feedScreenCollectionView.contentOffset.y > 0)  {
                self.lastContentOffset = scrollView.contentOffset.y
                header.isHidden = true
            }
            else{
                self.lastContentOffset = scrollView.contentOffset.y
    
            }
    
    
        }
    
    
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardFrameChangeNotification(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        }
    
        var offsetY:CGFloat = 0
    
        @objc func keyboardFrameChangeNotification(notification: Notification) {
    
        }
    
    
    }
    
    
    class feedViewCell:UICollectionViewCell{
    
        @IBOutlet weak var feedImageView: UIImageView!
        @IBOutlet weak var feedLabel: UILabel!
    
    
        override func awakeFromNib() {
            super.awakeFromNib()
            feedLabel.translatesAutoresizingMaskIntoConstraints = false
            feedImageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
            feedImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
            feedImageView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
            feedImageView.bottomAnchor.constraint(equalTo: self.feedLabel.topAnchor).isActive = true
    
            feedImageView.translatesAutoresizingMaskIntoConstraints = false
            feedLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
            feedLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
            feedLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
            feedLabel.topAnchor.constraint(equalTo: self.feedImageView.bottomAnchor).isActive = true
            feedLabel.textAlignment = .center
    
        }
    
    }
    
    //should it be done with protocol we will have to reassess
    protocol HideHeaderScrollViewDelegate {
        func hideHeaderView(hide: Bool)
    }
    
    protocol printDelegateWorkedDelegate {
        func printDelegateWorkedDelegate()
    }
    
    class feedViewHeader:UICollectionReusableView,UITextFieldDelegate,UICollectionViewDelegate{
    
        @IBOutlet weak var feedSearchBar: UITextField!
    
        var delegateWorked:printDelegateWorkedDelegate?
    
        var VC:ViewController!
        var collectionView:UICollectionView?
        var stringToBeSet = "String to be set"
    //
        override func awakeFromNib() {
            super.awakeFromNib()
            print("Im in awakeFromNib in header")
    
            feedSearchBar.delegate = self
            feedSearchBar.autocorrectionType = .no
            feedSearchBar.keyboardType = .default
            feedSearchBar.addTarget(self, action: #selector(feedViewHeader.textFieldDidChange), for: .editingChanged)
            self.feedSearchBar.borderStyle = .roundedRect
            self.feedSearchBar.layer.borderColor = UIColor.black.cgColor
            self.feedSearchBar.layer.borderWidth = 4
            var searchBarHeight = self.feedSearchBar.bounds.height
            self.feedSearchBar.rightViewMode = .always
        }
    
    
        @objc func viewTapped(gestureRecognizer:UIGestureRecognizer){
    
            if  feedSearchBar.isFirstResponder{
                feedSearchBar.resignFirstResponder()
            }
        }
    
    //
    //
    //    //Text Field Delegate
       func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            VC.feedScreenCollectionView.reloadData()
            return true
        }
    
        /// Helper to dismiss keyboard
        @objc func didStopEditing() {
        }
    
        func textFieldDidEndEditing(_ textField: UITextField) {
            UIView.setAnimationCurve(UIViewAnimationCurve.easeInOut)
            UIView.animate(withDuration: 0.2) {
                self.VC.view.frame.origin.y = 0
            }
        }
    ////
        @objc func textFieldDidChange(){
            guard(!(feedSearchBar.text?.isEmpty)!) else{
                VC.currentTagsArray = VC.genericTagsArray
                VC.feedScreenCollectionView.reloadData()
                return
            }
    
            VC.currentTagsArray = VC.genericTagsArray.filter({letter -> Bool in
                if feedSearchBar.text!.count > letter.count{
                    return false
                }
                let stringRange = letter.index(letter.startIndex, offsetBy: feedSearchBar.text!.count)
                let subword = letter[..<stringRange]
                return subword.lowercased().contains(feedSearchBar.text!.lowercased())
            })
    
            if VC.currentTagsArray.isEmpty{
                VC.currentTagsArray.insert(feedSearchBar.text!, at: 0)
            }
    
            VC.feedScreenCollectionView.reloadData()
       }
    
    
    }
    
    extension Notification.Name{
        static let showKeyboard = Notification.Name("showKeyboard")
    }
    class KeyboardSlider: NSObject {
        // variables to hold and process information from the view using this class
        weak var view: UIView?
    
        @objc func keyboardWillShow(notification: NSNotification) {
            // method to move keyboard up
            // view?.frame.origin.y = 0 - getKeyboardHeight(notification as Notification)
            print("made it to keyboard will show")
        }
    
        func getKeyboardHeight(_ notification:Notification) -> CGFloat {
            // get exact height of keyboard on all devices and convert to float value to return for use
            let userInfo = notification.userInfo
            let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
            return keyboardSize.cgRectValue.height
        }
    
        func subscribeToKeyboardNotifications(view: UIView) {
            // assigning view to class' counterpart
            self.view = view
            // when UIKeyboardWillShow do keyboardWillShow function
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
        }
    
        func unsubscribeFromKeyboardNotifications() {
            NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
        }
    }
    
    0 回复  |  直到 8 年前
    推荐文章