iOS应用中混合使用SwiftUI和UIKit代码库的挑战
Imagine you are a software engineer, or you really are. You create iOS apps on a daily basis. You use only the latest and finest trends in mobile development, such as SPM, Swift Data, and, of course, SwiftUI. Life couldn’t be better. But reality is cruel. And in real life you probably need to maintain and develop an application that was written several years ago when these technologies didn’t exist at all.
想象一下,您是一名软件工程师,或者您真的是。您每天都在创建iOS应用程序。您只使用移动开发中最新和最好的趋势,例如SPM、Swift Data和当然是SwiftUI。生活再好不过了。但现实是残酷的。在现实生活中,您可能需要维护和开发一个在这些技术根本不存在的几年前编写的应用程序。
Due to your natural curiosity and desire to build top-notch products, you still strive to integrate the best approaches in your app. The Medium iOS team is not an exception. And given that our codebase dates back to 2013, it has a bunch of UIKit views.
由于您的自然好奇心和渴望构建一流产品,您仍然努力将最佳方法集成到您的应用程序中。Medium iOS团队也不例外。鉴于我们的代码库可以追溯到2013年,它拥有大量的UIKit视图。
In this post, I’d like to cover some differences SwiftUI and UIKit interactions, pitfalls, and things to consider before making the decision to upgrade your views from UIKit to SwiftUI.
在本文中,我想介绍一些SwiftUI和UIKit之间的交互差异、陷阱以及在决定将视图从UIKit升级到SwiftUI之前需要考虑的事项。
- Integration Complexity & Code Duplication
- 集成复杂性和代码重复
Integrating SwiftUI views into a UIKit project might not be as seamless as anticipated. SwiftUI uses a different approach with its declarative syntax and layout system compared to UIKit’s imperative approach. SwiftUI views can be embedded within UIKit using UIHostingController
. One of the most common problems we faced is sizing, especially for cells (showing SwiftUI view as UITableViewCell
or UICollectionViewCell
when they don’t have fixed dimensions).
将SwiftUI视图集成到UIKit项目中可能并不像预期的那样无缝。SwiftUI使用其声明性语法和布局系统与UIKit的命令式方法不同。可以使用UIHostingController
将SwiftUI视图嵌入到UIKit中。我们面临的最常见问题之一是大小调整,特别是对于单元格(在它们没有固定尺寸时显示SwiftUI视图作为UITableViewCell
或UICollectionViewCell
)。
When it comes to scroll tracking, SwiftUI and UIKit have different API and approaches for this. The differences start even in details like scroll offset. In UIKit, it has a negative v...