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

Swift中如何获取导航栏按钮项标题?Action Outlet调用无法获取标题

解决Swift中获取导航栏按钮标题的问题

嘿,我来帮你搞定这个问题!你遇到的核心问题和解决方法我都整理好了:

一、先修复你的IBAction代码问题

你写的代码里sender是Any类型,Swift没法识别它具体是UIBarButtonItem,自然就找不到title属性啦。这里有两种简单的修复方式:

方式1:直接指定sender的类型

修改IBAction的参数类型为UIBarButtonItem,这样就能直接访问title了:

@IBAction func rightBarButtonItemDidTap(_ sender: UIBarButtonItem) {
    // 用??处理可选值,避免标题为nil时打印空内容
    print(sender.title ?? "该按钮没有设置标题")
}

方式2:安全转换sender类型

如果没法修改参数类型(比如某些场景下的限制),可以用guard let做安全类型转换,防止崩溃:

@IBAction func rightBarButtonItemDidTap(_ sender: Any) {
    guard let barButton = sender as? UIBarButtonItem else {
        print("当前触发事件的不是导航栏按钮")
        return
    }
    print(barButton.title ?? "该按钮没有设置标题")
}

二、通用的导航栏按钮标题获取方法

如果不需要在点击事件里获取,而是想在其他地方直接读取导航栏按钮的标题,可以直接访问navigationItem的对应属性:

// 获取右侧导航栏按钮的标题
if let rightBarButtonTitle = navigationItem.rightBarButtonItem?.title {
    print("右侧按钮标题:\(rightBarButtonTitle)")
}

// 获取左侧导航栏按钮的标题
if let leftBarButtonTitle = navigationItem.leftBarButtonItem?.title {
    print("左侧按钮标题:\(leftBarButtonTitle)")
}

内容的提问来源于stack exchange,提问作者snehal B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:29:56