You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UIKit中点击导航栏右侧按钮跳转SwiftUI视图的实现问题

解决UIKit导航栏按钮跳转SwiftUI视图的问题

报错原因

你当前的错误是因为UIBarButtonItem的action参数需要传入Selector(选择器),而不是直接调用editButtonCustomizeView()创建视图实例,类型不匹配导致报错。

完整修正代码

  1. 修正导航栏按钮的创建逻辑,将action指向专门的点击触发方法:
override func viewDidLoad() {   
    super.viewDidLoad()
    // 修正action参数为Selector,指向点击方法
    let editButton = UIBarButtonItem(image: editImage, style: .plain, target: self, action: #selector(editButtonTapped))
    // 将按钮添加到导航栏右侧
    navigationItem.rightBarButtonItem = editButton
}
  1. 添加按钮点击触发的方法,在方法内包装并跳转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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:35:27