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

如何为UIButton设置UIBackgroundConfiguration?iOS15找不到属性怎么办

UIButton configuration属性不可用的原因

  • 首先确认项目的Mac Catalyst最低部署版本是否为15.0及以上:该属性仅支持iOS 15.0+、Mac Catalyst 15.0+,若部署版本低于要求,Xcode会默认隐藏该API。
  • 若你使用的是Interface Builder创建的按钮:需要先在IB面板中将按钮的Style属性从默认的Default改为其他支持Configuration的样式(如Plain、Gray、Tinted、Filled),否则按钮默认使用旧版渲染逻辑,不会暴露configuration属性。
  • 若你使用纯代码创建按钮:不要使用旧版+[UIButton buttonWithType:]的初始化方式(尤其不要用UIButtonTypeCustom),建议使用iOS 15新增的+[UIButton buttonWithConfiguration:primaryAction:]方法创建,或手动给旧方式创建的按钮赋值configuration对象启用新特性。

正确的代码实现方式

UIBackgroundConfiguration是UIButtonConfiguration的子属性,不能直接赋值给UIButton对象,需要按照如下步骤使用:

// 先做系统版本判断
if (@available(iOS 15.0, macCatalyst 15.0, *)) {
    // 1. 初始化带configuration的按钮
    UIButton *testButton = [UIButton buttonWithConfiguration:[UIButtonConfiguration plainConfiguration] primaryAction:nil];
    testButton.frame = CGRectMake(50, 50, 200, 44);
    [self.view addSubview:testButton];
    
    // 2. 创建并配置背景对象
    UIBackgroundConfiguration *bgConfig = [UIBackgroundConfiguration listPlainCellConfiguration];
    bgConfig.strokeColor = UIColor.labelColor;
    // 可按需配置其他背景属性:strokeWidth、cornerRadius、backgroundColor等
    
    // 3. 将背景配置赋值给按钮configuration
    UIButtonConfiguration *btnConfig = testButton.configuration;
    btnConfig.background = bgConfig;
    // 最后将修改后的configuration写回按钮
    testButton.configuration = btnConfig;
}

如果是Interface Builder创建的按钮,在修改配置前先手动初始化configuration即可:

if (@available(iOS 15.0, macCatalyst 15.0, *)) {
    // 给IB创建的旧样式按钮启用configuration特性
    self.ibButton.configuration = [UIButtonConfiguration plainConfiguration];
    // 后续修改逻辑和上面一致
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:48:01