菜鸟教程小白 发表于 2022-12-12 13:27:18

ios - UIKeyboard 出现触发滚动事件,然后关闭键盘


                                            <p><p>我遇到了一个我一直无法解决的奇怪问题。</p>

<p>我在 TableView 的 TableViewCell 中有一个文本字段。当我点击单元格时,会出现一个键盘。我有以下代码可以关闭所述键盘:</p>

<pre><code>-(void) scrollViewDidScroll:(UIScrollView *)scrollView {
    ;
}
</code></pre>

<p>问题是,当 TextField 低于键盘顶部的位置时,TableView 会滚动以使其可见。这反过来会触发 scrollViewDidScroll 方法,然后关闭键盘。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>有道理——<code>scrollViewDidScroll:</code> 委托(delegate)方法<em>每次</em>都会调用tableview 滚动。因此,如果您的 <code>scrollViewDidScroll:</code> 关闭键盘,那么当应用程序自动调整(滚动)tableview 内容偏移量以考虑键盘时,它会自行关闭。</p>

<p>您将希望以不同的方式实现键盘关闭。对于一种解决方案,将您的 UITableViewController 设为 <code>UITextFieldDelegate</code>。然后,实现 <code>textFieldShouldReturn:</code>,您可以在其中调用 <code></code> 或 <code></code>(参见 <a href="https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html" rel="noreferrer noopener nofollow">Managing the Keyboard (Apple)</a>更多细节)。 </p>

<p>我想你正在寻找的效果是,如果用户触摸 UITextField 或键盘之外的任何地方,键盘就会被关闭。为此,我会考虑实现 <code>touchesBegan:</code> (如 <a href="http://www.techotopia.com/index.php/Writing_iOS_7_Code_to_Hide_the_Keyboard" rel="noreferrer noopener nofollow">Techotopia</a> 中所述)或使用 <code>UITapGestureRecognizer</code>(如 <a href="https://stackoverflow.com/questions/2321038/dismiss-keyboard-by-touching-background-of-uitableview" rel="noreferrer noopener nofollow">this post</a> 中所述,请确保包含 <code>gestureRecognizer.cancelsTouchesInView = NO;</code> 因为它建议在页面的下方)。 </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - UIKeyboard 出现触发滚动事件,然后关闭键盘,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/27746739/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/27746739/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - UIKeyboard 出现触发滚动事件,然后关闭键盘