惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
Jina AI
Jina AI
博客园_首页
WordPress大学
WordPress大学
罗磊的独立博客
小众软件
小众软件
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
爱范儿
爱范儿
The Cloudflare Blog
GbyAI
GbyAI
C
Check Point Blog
腾讯CDC
MyScale Blog
MyScale Blog
有赞技术团队
有赞技术团队
博客园 - 聂微东
IT之家
IT之家
雷峰网
雷峰网
H
Help Net Security
博客园 - 叶小钗
美团技术团队
D
DataBreaches.Net

Peter Steinberger

OpenClaw, OpenAI and the future | Peter Steinberger Shipping at Inference-Speed | Peter Steinberger The Signature Flicker | Peter Steinberger Just Talk To It - the no-bs Way of Agentic Engineering | Peter Steinberger Claude Code Anonymous | Peter Steinberger Live Coding Session: Building Arena | Peter Steinberger My Current AI Dev Workflow | Peter Steinberger Essential Reading for Agentic Engineers - August 2025 | Peter Steinberger Just One More Prompt | Peter Steinberger Poltergeist: The Ghost That Keeps Your Builds Fresh | Peter Steinberger Don't read this Startup Slop | Peter Steinberger Essential Reading for Agentic Engineers - July 2025 | Peter Steinberger Self-Hosting AI Models After Claude's Usage Limits | Peter Steinberger Logging Privacy Shenanigans | Peter Steinberger VibeTunnel's first AI-anniversary | Peter Steinberger Making AppleScript Work in macOS CLI Tools: The Undocumented Parts | Peter Steinberger Peekaboo 2.0 – Free the CLI from its MCP shackles | Peter Steinberger Command your Claude Code Army, Reloaded | Peter Steinberger Essential Reading for Agentic Engineers | Peter Steinberger Slot Machines for Programmers: How Peter Builds Apps 20x Faster with AI | Peter Steinberger My AI Workflow for Understanding Any Codebase | Peter Steinberger stats.store: Privacy-First Sparkle Analytics | Peter Steinberger Showing Settings from macOS Menu Bar Items: A 5-Hour Journey | Peter Steinberger VibeTunnel: Turn Any Browser into Your Mac's Terminal | Peter Steinberger Vibe Meter 2.0: Calculating Claude Code Usage with Token Counting | Peter Steinberger llm.codes: Make Apple Docs AI-Readable | Peter Steinberger Automatic Observation Tracking in UIKit and AppKit: The Feature Apple Forgot to Mention | Peter Steinberger Peekaboo MCP – lightning-fast macOS screenshots for AI agents | Peter Steinberger Migrating 700+ Tests to Swift Testing: A Real-World Experience | Peter Steinberger Commanding Your Claude Code Army | Peter Steinberger
Disabling Keyboard Avoidance in SwiftUI's UIHostingContro...
Peter Steinberger · 2020-09-22 · via Peter Steinberger

While SwiftUI is still being cooked hot, it’s already really useful and can replace many parts of your app. And with UIHostingController, it can easily be mixed with existing UIKit code. With iOS 14, the SwiftUI team at Apple added keyboard avoidance logic to the hosting controller, which can result in pretty ugly scrolling behavior.

When Keyboard Avoidance Is Unwanted

When the keyboard is visible and UIHostingController doesn’t own the full screen, views try to move away from the keyboard. This has been a frustrating bug for many, and it’s especially bad if you embed UIHostingController as table view cells or collection view cells.1

{% twitter https://twitter.com/thesamcoe/status/1306350596715282434?s=20 %}

While it seems that there are some weird workarounds if you use iOS 14.2, this seems unreliable, and folks still need a solution for iOS 14.0.

Fixing Strategies

While I’ve not been directly affected by this issue, I was curious and tried to fix it a while back. My first attempt was adding .ignoresSafeArea(.keyboard) to the SwiftUI view, but this doesn’t seem to change anything.

When the official ways don’t work, there’s always the runtime, so I’ve been inspecting the view controller’s methods and looking for something to poke at. As the class is written in Swift, there’s very little that’s exposed to the Objective-C runtime — only methods that are overridden from UIViewController or exposed with @objc will show up here. I could potentially use a Swift mirror to see the remaining functions, but changing them is difficult. There was nothing interesting, so I reported a r̶a̶d̶a̶r̶ Feedback2 and that was it.

A few days later, I was reading Samuel Défago’s brilliant blog post about how he wrapped UICollectionView for Swift. In part 3, he presents a fix to an issue with safeAreaInsets in UIHostingController. This is done by modifying the view class. It motivated me to take a closer look at the view — maybe Apple was hiding the keyboard avoidance logic there?

po SwiftUI._UIHostingView<KeyboardSwiftUIBug.ContentView>.self.perform("_shortMethodDescription")

▿ Optional<Unmanaged<AnyObject>>
  ▿ some : Unmanaged<AnyObject>
    - _value : <_TtGC7SwiftUI14_UIHostingViewV18KeyboardSwiftUIBug11ContentView_: 0x7fff87103a28>:
in _TtGC7SwiftUI14_UIHostingViewV18KeyboardSwiftUIBug11ContentView_:
	Properties:
		@property (nonatomic, readonly) struct UIEdgeInsets safeAreaInsets;
		@property (nonatomic, retain) UIColor* backgroundColor;
		@property (nonatomic, readonly) unsigned long _axesForDerivingIntrinsicContentSizeFromLayoutSize;
		@property (nonatomic, readonly) BOOL _layoutHeightDependsOnWidth;
	Instance Methods:
		- (void) dealloc; (0x7fff566e9320)
		- (id) initWithCoder:(id)arg1; (0x7fff566e91e0)
		- (id) backgroundColor; (0x7fff566eaab0)
		- (void) setBackgroundColor:(id)arg1; (0x7fff566eab30)
		- (id) initWithFrame:(struct CGRect)arg1; (0x7fff566ec710)
		- (void) layoutSubviews; (0x7fff566ea040)
		- (void) traitCollectionDidChange:(id)arg1; (0x7fff566ea630)
		- (struct CGSize) sizeThatFits:(struct CGSize)arg1; (0x7fff566eadb0)
		- (struct UIEdgeInsets) safeAreaInsets; (0x7fff566ea790)
		- (void) didUpdateFocusInContext:(id)arg1 withAnimationCoordinator:(id)arg2; (0x7fff566ec230)
		- (id) preferredFocusEnvironments; (0x7fff566ec150)
		- (void) safeAreaInsetsDidChange; (0x7fff566ea6c0)
		- (void) didMoveToSuperview; (0x7fff566e9df0)
		- (void) _geometryChanged:(void*)arg1 forAncestor:(id)arg2; (0x7fff566e9ef0)
		- (id) _childFocusRegionsInRect:(struct CGRect)arg1 inCoordinateSpace:(id)arg2; (0x7fff566ec080)
		- (struct ?) _baselineOffsetsAtSize:(struct CGSize)arg1; (0x7fff566eacd0)
		- (unsigned long) _axesForDerivingIntrinsicContentSizeFromLayoutSize; (0x7fff566eabd0)
		- (void) contentSizeCategoryDidChange; (0x7fff566ea5c0)
		- (void) keyboardWillShowWithNotification:(id)arg1; (0x7fff566ec4f0)
		- (void) keyboardWillHideWithNotification:(id)arg1; (0x7fff566ec5a0)
		- (void) externalEnvironmentDidChange; (0x7fff566edd40)
		- (id) makeViewDebugData; (0x7fff566ec5f0)
		- (void) _geometryChanges:(id)arg1 forAncestor:(id)arg2; (0x7fff566e9e20)
(UIView ...)

UIHostingView looks very interesting indeed.3 Based on the design, it seems that at some point, Apple considered giving us both the hosting controller and the hosting view, but then opted for just the controller — it wouldn’t make sense to pack all that logic into the view if the controller was always planned.

Looking at the output, I see there are quite a few Swift methods that have been exposed to the Objective-C runtime. keyboardWillShowWithNotification: and keyboardWillHideWithNotification: look exactly like candidates to tweak. We’re really lucky here that the SwiftUI engineers didn’t use the block-based NSNotification API4, but instead used the target/selector approach — which not only needs @objc annotations to work, but also opens the door for our shenanigans.

Subclassing at Runtime

We want to replace the implementation of keyboardWillShowWithNotification: with an empty one. The classic solution here would be swizzling, but that would modify all instances of UIHostingController, and we don’t know if the view class is used somewhere else. It might work, but it seems risky.

A better strategy is to modify only instances we control, and we can do that via dynamic subclassing. It’s my favorite way to modify behavior on a per-object basis. In fact, I wrote an entire Swift library called InterposeKit to make this easy:

import SwiftUI
import InterposeKit

extension UIHostingController {
convenience public init(rootView: Content, ignoresKeyboard: Bool) {
    self.init(rootView: rootView)

    if ignoreKeyboard {
        _ = try? self.view.hook(NSSelectorFromString("keyboardWillShowWithNotification:")) { (
            store: TypedHook<@convention(c) (AnyObject, Selector, AnyObject) -> Void,
                             @convention(block) (AnyObject, AnyObject) -> Void>) in { _, _ in }
        }
    }
}
}

Dynamic subclassing isn’t very tricky, but the challenge is to write it in a way where it fails gracefully if the private API we modify is changed. InterposeKit adds a lot of error handling next to a convenient API so that you make fewer mistakes and have a more stable app. It’ll throw an error if the selection no longer exists or has a different type than the one you expect.

We can achieve something similar using built-in methods:

extension UIHostingController {
convenience public init(rootView: Content, ignoresKeyboard: Bool) {
    self.init(rootView: rootView)

    if ignoresKeyboard {
        guard let viewClass = object_getClass(view) else { return }

        let viewSubclassName = String(cString: class_getName(viewClass)).appending("_IgnoresKeyboard")
        if let viewSubclass = NSClassFromString(viewSubclassName) {
            object_setClass(view, viewSubclass)
        }
        else {
            guard let viewClassNameUtf8 = (viewSubclassName as NSString).utf8String else { return }
            guard let viewSubclass = objc_allocateClassPair(viewClass, viewClassNameUtf8, 0) else { return }

            if let method = class_getInstanceMethod(viewClass, NSSelectorFromString("keyboardWillShowWithNotification:")) {
                let keyboardWillShow: @convention(block) (AnyObject, AnyObject) -> Void = { _, _ in }
                class_addMethod(viewSubclass, NSSelectorFromString("keyboardWillShowWithNotification:"),
                                imp_implementationWithBlock(keyboardWillShow), method_getTypeEncoding(method))
            }
            objc_registerClassPair(viewSubclass)
            object_setClass(view, viewSubclass)
        }
    }
}
}

See my gist for a version that also removes safeAreaInsets. Who would’ve thought that runtime trickery is still useful in SwiftUI times?

If this is useful to you, ping @steipete on Twitter!

  1. Apple Folks: FB8698723 — Provide API in UIHostingController to disable keyboard avoidance for SwiftUI views. ↩

  2. If you want to try this for yourself, I’ve prepared an example here. ↩

  3. The makeViewDebugData method also looks pretty interesting… ↩

  4. The block-based notification API nowadays is inconvenient, as it doesn’t automatically deregister observers — using the target/action one is simpler, as these observers have automatically deregistered since iOS 9. ↩