Masquer le clavier lorsque vous faites défiler UITableView

dans mon application je veux cacher le clavier quand je commence à faire défiler UITableView. Je cherche à ce sujet sur internet, et la plupart des réponses sont des sous-classes UITableView (/q/tapping-a-uiscrollview-to-hide-the-keyboard-12031/"MyUITableView.h" @implementation MyUITableView - (nul)scrollViewDidScroll: (UIScrollView *)scrollView{ NSLog (@"delegate scrollView"); / / ceci ne fonctionne pas [super scrollViewDidScroll: scrollView]; } - (nul)touchesBegan: (NSSet *)touche avecevent: (Unievent *)événement { NSLog (@"delegate myuitable viewtouchesbegan"); / / work only here [délégué myuitable viewtouchesbegan]; [super touchesBegan: touche avecevent: événement]; } - (void)dealloc { ...

j'utilise cette classe comme ça. Mais la fonction de délégué myuitable viewtouchesbegan ne fonctionne pas dans ViewController

.h

#import <UIKit/UIKit.h>
#import "MyUITableView.h"

@interface FirstViewController : UIViewController <UITableViewDelegate, UISearchBarDelegate, MyUITableViewDelegate> {
    MyUITableView *myTableView;
    UISearchBar *searchBar; 
}

@property(nonatomic,retain) IBOutlet MyUITableView *myTableView;
...

.m

- (void) myUITableViewTouchesBegan{
    NSLog(@"myUITableViewTouchesBegan");
    [searchBar resignFirstResponder];
}

j'ai quelques problèmes avec cette implémentation:

1) myuitable viewtouchesbegan dont le travail en vue contrôleur

2) NSLog from MyUITableView.m - NSLog (@"delegate myuitable viewtouchesbegan"); travailler seulement quand je touche la table. Comment ça se fait que ça marche aussi quand je commence à défiler?

J'ai essayé de surcharger scrollViewDidScroll mais comiler a dit que MyUITableVIew pourrait être don't respond sur cette chaîne de caractères [super scrollViewDidScroll: scrollView];

99
demandé sur olegi 2010-12-09 17:36:31

6 réponses

Je ne sais pas pourquoi vous devez sous-classe UITableView pour cela.

dans le contrôleur de vue qui contient la vue UITableView, essayez d'ajouter ceci:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [searchBar resignFirstResponder];
}
131
répondu 2010-12-09 15:28:23

voici le moyen le plus propre pour atteindre cet objectif dans iOS 7.0 et au-dessus:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

ou à rejeter quand toucher:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

ou dans Swift:

tableView.keyboardDismissMode = .onDrag

ou à rejeter de façon interactive lors du défilement:

tableView.keyboardDismissMode = .interactive
325
répondu Pei 2017-08-16 15:48:45

vous pouvez faire ce droit dans Interface Builder. Sélectionnez votre UITableView et ouvrez L'Inspecteur des attributs. Dans la section Scroll View, sélectionnez clavier dans le champ rejeter sur la traînée .

enter image description here

104
répondu Kyle Clegg 2014-06-18 21:40:11

juste pour ajouter une mise à jour aux réponses ci-dessus. Ce qui suit a fonctionné pour moi dans Swift 1.2

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag

ou

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive
37
répondu Gareth Jones 2015-02-22 22:11:11

solution de travail sans écrire une seule ligne de code dans votre contrôleur:

comme votre question Est de manipuler le clavier de cache avec une condition seulement (sur le rouleau). Mais ici, je recommande une solution pour gérer textfield et keyboard ensemble qui fonctionne comme le charme pour UIViewController, Uitablview et UIScrollView. Le fait intéressant est que Vous n'avez pas besoin d'écrire une seule ligne de code.

ici vous allez: TPKeyboardAvoiding - une solution géniale pour manipuler le clavier et faire défiler

1
répondu iDevAmit 2018-07-23 02:58:28

tâche

masquer le clavier par programmation lorsque vous faites défiler UITableView dans Swift 3

détails

xCode 8.2.1, swift 3

Solution

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if !tableView.isDecelerating {
        view.endEditing(true)
    }
}

Échantillon Complet

ViewController

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!


    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
    }
}

// MARK: - UITableViewDataSource

extension ViewController: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  UITableViewCell(style: .subtitle, reuseIdentifier: nil)
        cell.textLabel?.text = "Title"
        cell.detailTextLabel?.text = "\(indexPath)"
        return cell
    }
}

// MARK: - UITableViewDelegate

extension ViewController: UITableViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !tableView.isDecelerating {
            view.endEditing(true)
        }
    }
}

StoryBoard

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16D32" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_4399357" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <searchBar contentMode="redraw" translatesAutoresizingMaskIntoConstraints="NO" id="wU1-dV-ueB">
                                <rect key="frame" x="0.0" y="20" width="375" height="44"/>
                                <textInputTraits key="textInputTraits"/>
                            </searchBar>
                            <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" keyboardDismissMode="interactive" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="L52-4c-UtT">
                                <rect key="frame" x="0.0" y="64" width="375" height="603"/>
                                <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                            </tableView>
                        </subviews>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="wU1-dV-ueB" firstAttribute="bottom" secondItem="L52-4c-UtT" secondAttribute="top" id="0WF-07-qY1"/>
                            <constraint firstAttribute="trailing" secondItem="wU1-dV-ueB" secondAttribute="trailing" id="3Mj-h0-IvO"/>
                            <constraint firstItem="wU1-dV-ueB" firstAttribute="leading" secondItem="L52-4c-UtT" secondAttribute="leading" id="8W5-9j-2Rg"/>
                            <constraint firstItem="wU1-dV-ueB" firstAttribute="trailing" secondItem="L52-4c-UtT" secondAttribute="trailing" id="crK-dR-UYf"/>
                            <constraint firstItem="wU1-dV-ueB" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="mPe-bp-Dxw"/>
                            <constraint firstItem="L52-4c-UtT" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="oIo-DI-vLh"/>
                            <constraint firstItem="wU1-dV-ueB" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" id="tVC-UR-PA4"/>
                        </constraints>
                    </view>
                    <connections>
                        <outlet property="searchBar" destination="wU1-dV-ueB" id="xJf-bq-4t9"/>
                        <outlet property="tableView" destination="L52-4c-UtT" id="F0T-yb-h5r"/>
                    </connections>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-79.200000000000003" y="137.18140929535232"/>
        </scene>
    </scenes>
</document>

résultat

enter image description here

0
répondu Vasily Bodnarchuk 2017-03-05 08:04:19