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

Swift类遵守UIContentConfiguration协议,Objective-C为何无法识别?

在Objective-C项目中使用Swift实现的UIContentConfiguration遇到的问题

我正尝试在以Objective-C为主的项目中使用Swift编写的类,场景涉及UITableViewCell的UIContentConfiguration。

Swift实现代码

@objc class MyCellConfiguration: NSObject, UIContentConfiguration {
    let label: String

    @objc init(label: String) {
        self.label = label
    }

    func makeContentView() -> UIView & UIContentView {
        return MyCellContent(self)
    }

    func updated(for state: UIConfigurationState) -> Self {
        return self
    }
}

class MyCellContent: UIView, UIContentView {
    // 该类的实现与问题无关
}

Objective-C中的问题表现

在Objective-C代码中配置单元格时,会出现编译器警告,忽略警告后运行到该代码处应用会挂起。

Objective-C代码如下:

#import "MyApp-Swift.h" // 已导入桥接文件

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:key forIndexPath:indexPath];

MyCellConfiguration *config = [[MyCellConfiguration alloc] initWithLabel:@"Some Label"];
cell.contentConfiguration = config; // 此处出现警告

收到的编译器警告为:

Assigning to 'id<UIContentConfiguration> _Nullable' from incompatible type 'MyCellConfiguration *__strong'

疑问点

Swift代码中可以正常识别MyCellConfiguration遵守UIContentConfiguration协议,例如以下代码可正常编译:

let cell = UITableViewCell(style: .default, reuseIdentifier: "foo")
cell.contentConfiguration = MyCellConfiguration(label: "foo")

使用环境:Xcode 15.0,macOS 13.6.1


内容的提问来源于stack exchange,提问作者HangarRash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:43:32