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

SwiftUI TipKit PopoverTip 自定义样式:避免占满全屏宽度

解决SwiftUI TipKit popoverTip提示框占满屏幕宽度的问题

默认情况下,TipKit的popoverTip会让提示框尽可能占满屏幕可用宽度,要缩小提示框尺寸,核心是自定义Tip的内容视图并限制其宽度,以下是两种可行方案:

方案一:固定最大宽度

修改你的LongPressAlarmTooltip结构体,在其body中给内容添加宽度限制:

@available(iOS 17.0, *)
struct LongPressAlarmTooltip: Tip {
    var title: Text {
        Text("长按设置提醒")
    }
    
    var message: Text? {
        Text("长按卡片可快速设置闹钟提醒")
    }

    // 自定义提示框内容,控制尺寸
    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            title
            message
        }
        .padding()
        .frame(maxWidth: 280) // 设定最大宽度
        .background(Color(.systemBackground))
        .cornerRadius(12)
    }
}

方案二:相对屏幕宽度(适配性更好)

如果想要提示框宽度随屏幕尺寸自适应,可以用containerRelativeFrame设置相对屏幕的占比:

@available(iOS 17.0, *)
struct LongPressAlarmTooltip: Tip {
    var title: Text {
        Text("长按设置提醒")
    }
    
    var message: Text? {
        Text("长按卡片可快速设置闹钟提醒")
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            title
            message
        }
        .padding()
        .containerRelativeFrame(.horizontal, fraction: 0.7) // 占屏幕宽度的70%
        .background(Color(.systemBackground))
        .cornerRadius(12)
    }
}

修改后的调用代码

你的makeScheduledCardWithTooltip函数无需额外改动,保持原有逻辑即可:

@ViewBuilder
func makeScheduledCardWithTooltip() -> some View {
    var shouldAddTooltip: Bool {
        //... 此处逻辑与当前问题无关
        return true
    }
            
    if shouldAddTooltip, #available(iOS 17.0, *) {
        let tip = LongPressAlarmTooltip()
        
        Rectangle()
            .popoverTip(tip, arrowEdge: .bottom)
    } else {
        Rectangle()
    }
}

原理说明:默认Tip的系统样式会拉伸至屏幕宽度,通过自定义Tip的body视图并主动限制宽度,就能覆盖默认的布局行为,让提示框按照你设定的尺寸显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:57:11