草庐IT

ios - iOS 键盘下的空白区域

coder 2023-09-22 原文

在我的 iOS 应用中,第二次显示键盘后,键盘下方有一个空白区域。

.?123后空格隐藏。

我删除了 keyboardWillShowNotificationkeyboardWillHideNotification 并且发生了同样的事情。我在 viewWillTransitionToSize:withTransitionCoordinator: 处调整了 UITextView 的大小,但我删除了调整大小的代码,但同样的事情发生了。

我的 iPhone 7 不会发生这种情况,但我的 iPad 6th gen 会发生这种情况。这很奇怪,因为它就在我的应用程序的这个特定 TextView 中。

有人遇到过这种情况吗?我在 Google 中找不到任何内容。

这里是 View Controller 的源代码:https://github.com/ColdGrub1384/Pyto/blob/master/Pyto/View%20Controllers/EditorViewController.swift

我使用其中包含 UITextView 的 View 来突出显示语法,但这与错误无关,因为我还使用标准 UITextView 进行了测试。

最佳答案

@objc protocol KeyboardConstraintListener: class
{
func didOpenKeyboard()
func didCloseKeyboard()
}

class KeyboardConstraint: NSLayoutConstraint
{
@IBOutlet
weak var listener: KeyboardConstraintListener?

@IBInspectable
var skipAutoCalculateMarginToBottom: Bool = false

@IBInspectable
var keepMarginWhenOpen: Bool = false

private var originalConstant: CGFloat = 0.0

override func awakeFromNib()
{
    super.awakeFromNib()
    self.originalConstant = self.constant

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(keyboardWillShow),
                                           name: UIResponder.keyboardWillShowNotification,
                                           object: nil)

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(keyboardWillHide),
                                           name: UIResponder.keyboardWillHideNotification,
                                           object: nil)
}

deinit
{
    NotificationCenter.default.removeObserver(self)
}

@objc func keyboardWillShow(notification: Notification)
{
    self.listener?.didOpenKeyboard()
    self.updateConstant(notification: notification, showing: true)
}

@objc func keyboardWillHide(notification: Notification)
{
    self.listener?.didCloseKeyboard()
    self.updateConstant(notification: notification, showing: false)
}

private func updateConstant(notification: Notification, showing: Bool)
{
    let duration: TimeInterval = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double) ?? 0.2

    guard let endFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else
    {
        return
    }

    guard let firstView: UIView = self.getView(item: self.firstItem) else
    {
        return
    }

    guard let secondView: UIView = self.getView(item: self.secondItem) else
    {
        return
    }

    guard let superview: UIView = firstView.superview else
    {
        return
    }

    let keyboardHeight: CGFloat = (showing ? max(endFrame.size.height - self.modifier(view: secondView), 0.0) : 0.0)

    CATransaction.begin()
    CATransaction.setDisableActions(true)
    superview.layoutIfNeeded()
    CATransaction.commit()

    UIView.animate(
        withDuration: duration,
        delay: 0,
        options: [.curveLinear],
        animations:
        {
            self.constant = keyboardHeight + self.originalConstant
            superview.layoutIfNeeded()
    },
        completion: nil)
}

private func modifier(view: UIView) -> CGFloat
{
    guard let window: UIWindow = view.window else
    {
        return 0.0
    }

    guard let superview: UIView = view.superview else
    {
        return 0.0
    }

    guard !self.skipAutoCalculateMarginToBottom else
    {
        return 0.0
    }

    let origin: CGPoint = superview.convert(view.frame.origin, to: nil)
    let bottom = origin.y + view.bounds.size.height
    let expand = window.bounds.size.height - bottom
    return expand - (self.constant - self.originalConstant) - (self.keepMarginWhenOpen ? self.originalConstant : 0.0)
}

private func getView(item: AnyObject?) -> UIView?
{
    if let view = item as? UIView
    {
        return view
    }
    else if let view = (item as? UILayoutGuide)?.owningView
    {
        return view
    }
    return nil
}

创建一个约束使得 textView.bottom = safeArea.bottom

关于ios - iOS 键盘下的空白区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56103723/

有关ios - iOS 键盘下的空白区域的更多相关文章

  1. ruby - 在 Ruby 中用键盘诅咒数组浏览 - 2

    我正在尝试在Ruby中制作一个cli应用程序,它接受一个给定的数组,然后将其显示为一个列表,我可以使用箭头键浏览它。我觉得我已经在Ruby中看到一个库已经这样做了,但我记不起它的名字了。我正在尝试对soundcloud2000中的代码进行逆向工程做类似的事情,但他的代码与SoundcloudAPI的使用紧密耦合。我知道cursesgem,我正在考虑更抽象的东西。广告有没有人见过可以做到这一点的库或一些概念证明的Ruby代码可以做到这一点? 最佳答案 我不知道这是否是您正在寻找的,但也许您可以使用我的想法。由于我没有关于您要完成的工作

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  4. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  5. ruby-on-rails - 缺失区域;使用 :region option or export region name to ENV ['AWS_REGION' ] - 2

    我知道还有其他相同的问题,但他们没有解决我的问题。我不断收到错误:Aws::Errors::MissingRegionErrorinBooksController#create,缺少区域;使用:region选项或将区域名称导出到ENV['AWS_REGION']。但是,这是我的配置开发.rb:config.paperclip_defaults={storage::s3,s3_host_name:"s3-us-west-2.amazonaws.com",s3_credentials:{bucket:ENV['AWS_BUCKET'],access_key_id:ENV['AWS_ACCE

  6. ruby-on-rails - 如何为空白字段编写 rspec? [Rails3.1] - 2

    我使用rails3.1+rspec和factorygirl。我对必填字段(validates_presence_of)的验证工作正常。我如何让测试将该事实用作“成功”而不是“失败”规范是:describe"Addanindustrywithnoname"docontext"Unabletocreatearecordwhenthenameisblank"dosubjectdoind=Factory.create(:industry_name_blank)endit{shouldbe_invalid}endend但是我失败了:Failures:1)Addanindustrywithnona

  7. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  8. ruby - 返回空白页的最小 Capybara/Poltergeist 测试 - 2

    看来我正在回顾SO帖子中采取的步骤:Capybara,PoltergeistandPhantomjsandgivinganemptyresponseinbody.(如果你愿意,可以将其标记为重复,但我包含了一个最小的独立测试用例和版本号。)问题我做错了什么吗?我可以运行另一个可能有助于隔离问题的最小测试吗?文件:pgtest.rbrequire'rubygems'require'capybara'require'capybara/dsl'require'capybara/poltergeist'modulePGTestincludeCapybara::DSLextendselfdeft

  9. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

  10. ruby - IO::EAGAINWaitReadable:资源暂时不可用 - 读取会阻塞 - 2

    当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab

随机推荐