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

推荐订阅源

量子位
L
LINUX DO - 最新话题
TaoSecurity Blog
TaoSecurity Blog
S
Security Affairs
H
Hacker News: Front Page
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Hacker News: Ask HN
Hacker News: Ask HN
T
The Exploit Database - CXSecurity.com
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
Schneier on Security
Schneier on Security
云风的 BLOG
云风的 BLOG
I
InfoQ
The Register - Security
The Register - Security
T
Tor Project blog
T
Threat Research - Cisco Blogs
Spread Privacy
Spread Privacy
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The GitHub Blog
The GitHub Blog
MongoDB | Blog
MongoDB | Blog
Webroot Blog
Webroot Blog
Recent Announcements
Recent Announcements
Vercel News
Vercel News
F
Fortinet All Blogs
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
SecWiki News
SecWiki News
G
Google Developers Blog
N
Netflix TechBlog - Medium
U
Unit 42
Martin Fowler
Martin Fowler
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
O
OpenAI News
博客园 - 叶小钗
T
Tailwind CSS Blog
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Help Net Security
Help Net Security
A
About on SuperTechFans
Recorded Future
Recorded Future
Last Week in AI
Last Week in AI
Hugging Face - Blog
Hugging Face - Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
D
DataBreaches.Net
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
The Blog of Author Tim Ferriss
PCI Perspectives
PCI Perspectives
F
Full Disclosure
美团技术团队
L
Lohrmann on Cybersecurity
H
Hackread – Cybersecurity News, Data Breaches, AI and More

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 Code Signing and Notarization: Sparkle and Tears | Peter Steinberger Vibe Meter: Monitor Your AI Costs | Peter Steinberger Claude Code is My Computer | Peter Steinberger Stop Over-thinking AI Subscriptions | Peter Steinberger Introducing Demark: HTML in. MD out. Blink-fast. | Peter Steinberger The Future of Vibe Coding: Building with AI, Live and Unfiltered | Peter Steinberger MCP Best Practices | Peter Steinberger Finding My Spark Again | Peter Steinberger Top-Level Menu Visibility in SwiftUI for macOS | Peter Steinberger Fixing keyboardShortcut in SwiftUI | Peter Steinberger Supporting Both Tap and Long Press on a Button in SwiftUI | Peter Steinberger On Using Apple Silicon Mac Mini for Continuous Integration | Peter Steinberger Apple Silicon M1: A Developer's Perspective | Peter Steinberger Gardening Your Twitter: Curating Your Timeline | Peter Steinberger Gardening Your Twitter: Growing Your Followers | Peter Steinberger Forbidden Controls in Catalyst: Optimize Interface for Mac | Peter Steinberger The State of SwiftUI | Peter Steinberger Logging in Swift | Peter Steinberger Building with Swift Trunk Development Snapshots | Peter Steinberger Calling Super at Runtime in Swift | Peter Steinberger zld — A Faster Version of Apple's Linker | Peter Steinberger How to Fix LLDB: Couldn't IRGen Expression | Peter Steinberger Updating macOS on a Hackintosh | Peter Steinberger InterposeKit — Elegant Swizzling in Swift | Peter Steinberger The Great Mac Catalyst Text Input Crash Hunt | Peter Steinberger Jailbreaking for iOS Developers | Peter Steinberger Network Kernel Core Dump | Peter Steinberger How to macOS Core Dump | Peter Steinberger Kernel Panics and Surprise boot-args | Peter Steinberger The LG UltraFine 5K, kernel_task, and Me | Peter Steinberger Let's Try This Again | Peter Steinberger How We Work at PSPDFKit | Peter Steinberger Swizzling in Swift | Peter Steinberger WWDC for First-Timers, 2019 Edition | Peter Steinberger Challenges of Adopting Drag and Drop | Peter Steinberger Marzipan: Porting iOS Apps to the Mac | Peter Steinberger How to Use Slack and Not Go Crazy | Peter Steinberger Hardcore Debugging - Heavy Weapons for Hard Bugs | Peter Steinberger Binary Frameworks in Swift | Peter Steinberger Even Swiftier Objective-C | Peter Steinberger The Case for Deprecating UITableView | Peter Steinberger Running tests with Clang Address Sanitizer | Peter Steinberger UI testing on iOS, without busy waiting | Peter Steinberger Hiring a distributed team | Peter Steinberger Writing Good Bug Reports | Peter Steinberger Real-time collaboration, Apple, and you | Peter Steinberger Converting Xcode Test Runs to JUnit, the Fast Way | Peter Steinberger Efficient iOS Version Checking | Peter Steinberger Investigating Thread Safety of UIImage | Peter Steinberger Swifty Objective-C | Peter Steinberger Running UI Tests on iOS With Ludicrous Speed | Peter Steinberger A Pragmatic Approach to Cross-Platform | Peter Steinberger Surprises with Swift Extensions | Peter Steinberger Using ccache for Fun and Profit | Peter Steinberger UITableViewController designated initializer woes | Peter Steinberger Researching ResearchKit | Peter Steinberger The curious case of rotation with multiple windows on iOS 8 | Peter Steinberger UIKit Debug Mode | Peter Steinberger Retrofitting containsString: on iOS 7 | Peter Steinberger A Story About Swizzling "the Right Way™" and Touch Forwarding | Peter Steinberger Hacking with Aspects | Peter Steinberger Fixing UITextView On iOS 7 | Peter Steinberger Fixing What Apple Doesn't | Peter Steinberger How To Inspect The View Hierarchy Of Third-Party Apps | Peter Steinberger Fixing UISearchDisplayController On iOS 7 | Peter Steinberger Smart Proxy Delegation | Peter Steinberger Adding Keyboard Shortcuts To UIAlertView | Peter Steinberger How To Center Content Within UIScrollView | Peter Steinberger UIAppearance for Custom Views | Peter Steinberger Hacking Block Support Into UIMenuItem | Peter Steinberger
Disabling Keyboard Avoidance in SwiftUI's UIHostingController | Peter Steinberger
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. ↩