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

SwiftUI按钮单侧圆角实现的问题与解决

SwiftUI 实现左右分角圆角并排按钮问题解决

问题场景

需要在SwiftUI的HStack中实现两个并排按钮:

  • 左侧按钮仅左上角、左下角为圆角,其余两角保持直角
  • 右侧按钮仅右上角、右下角为圆角,其余两角保持直角

当前实现存在两个问题:

  1. 非目标角仍存在轻微圆角,无法完全保持直角
  2. 按钮默认灰色背景会透过圆角区域显示

初始实现代码

import SwiftUI

struct CustomButtons: View {
    // Action button properties
    var rightButtonText: String? = nil
    var leftButtonText: String? = nil
    var rightButtonAction: () -> Void = {}
    var leftButtonAction: () -> Void = {}
    
    var body: some View {
        HStack {
            Button(action: { leftButtonAction() }) {
                Text("No").padding()
            }.background (
                RoundSpecificCorners(corners: [.topLeft, .bottomLeft], radius: 15).fill(Color.actionButtonsBackground)
            )
                    
            Button(action: { rightButtonAction() }) {
                Text("Yes").padding()
            }.background (
                RoundSpecificCorners(corners: [.topRight, .bottomRight], radius: 15).fill(Color.actionButtonsBackground)
            )
        }
    }
}

struct RoundSpecificCorners: Shape {
    let corners: UIRectCorner
    let radius: CGFloat
    
    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(roundedRect: rect,
                                byRoundingCorners: corners,
                                cornerRadii: CGSize(width: radius, height: radius))
        return Path(path.cgPath)
    }
}

预期需求

  • 彻底消除左侧按钮右上角、右下角的轻微圆角,右侧按钮左上角、左下角的轻微圆角,保持这些角为纯直角
  • 移除圆角区域透出的按钮默认灰色背景

最终生效代码

var body: some View {
    HStack {
        Button(action: { leftButtonAction() }) {
            Text("No").padding().frame(minWidth: 0, maxWidth: .infinity)
        }.background( Color.blue )
        
        Button(action: { rightButtonAction() }) {
            Text("Yes").padding()
                
        }.background( Color.blue )
    }.mask(RoundedRectangle(cornerRadius: 25)).padding(.leading, 1).padding(.trailing, 1)
}

关键改动说明

  1. 给左侧按钮添加frame(minWidth: 0, maxWidth: .infinity),让它自动填充HStack剩余宽度,确保两个按钮紧密贴合无间隙
  2. 统一设置按钮背景色,覆盖默认灰色背景,解决透出问题
  3. 给整个HStack添加遮罩mask(RoundedRectangle(cornerRadius: 25)),通过整体遮罩实现左右圆角效果,避免单个按钮设置圆角带来的非目标角轻微圆角问题
  4. 添加左右各1pt的内边距,防止遮罩边缘过度裁切按钮内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 07:03:18