UIKit中点击导航栏右侧按钮跳转SwiftUI视图的实现问题
解决UIKit导航栏按钮跳转SwiftUI视图的问题
报错原因
你当前的错误是因为UIBarButtonItem的action参数需要传入Selector(选择器),而不是直接调用editButtonCustomizeView()创建视图实例,类型不匹配导致报错。
完整修正代码
- 修正导航栏按钮的创建逻辑,将
action指向专门的点击触发方法:
override func viewDidLoad() { super.viewDidLoad() // 修正action参数为Selector,指向点击方法 let editButton = UIBarButtonItem(image: editImage, style: .plain, target: self, action: #selector(editButtonTapped)) // 将按钮添加到导航栏右侧 navigationItem.rightBarButtonItem = editButton }
- 添加按钮点击触发的方法,在方法内包装并跳转SwiftUI视图:
@objc private func editButtonTapped() { // 用UIHostingController包装SwiftUI视图 let swiftUIContent = editButtonCustomizeView() let hostingController = UIHostingController(rootView: swiftUIContent) // 方式1:导航栈跳转(需当前VC在UINavigationController中) navigationController?.pushViewController(hostingController, animated: true) // 方式2:模态跳转(不需要导航栈时用) // present(hostingController, animated: true) }
关键注意事项
- 点击方法必须添加
@objc修饰,因为Selector只能识别Objective-C兼容的方法 - 新版Swift中
UIBarButtonItemStyle的枚举值已改为小写,建议将.Plain改为.plain - 若使用导航栈跳转,需确保当前视图控制器已嵌入
UINavigationController中,否则navigationController会为nil
内容的提问来源于stack exchange,提问作者Mai pa
相关产品推荐
相关产品推荐

