繁体   English   中英

SwiftUI如何制作连体按钮? (苹果系统)

[英]How do I make conjoined buttons in SwiftUI? (MacOS)

应用程序中存在一些按钮,例如TextEdit ,其中相邻按钮的两侧连接在一起。 有谁知道我如何复制这种视觉效果? 我在 SwiftUI 在 MacOS 上工作,对于 MacOS 10 和 11 的答案将不胜感激。

我认为这在 SwiftUI 中是不可能的,除非您想从头开始构建它。 您在 TextEdit 中看到的是一个允许多项选择的 NSSegmentedControl: https://developer.apple.com/design/human-interface-guidelines/macos/selectors/segmented-controls/

SwiftUI中,分段控件是使用Picker制作的,不允许多选。 最好的办法是将 NSSegmentedControl 包装在 NSHostingView 中。

使用 SwiftUI 复制这些按钮并不难。 这是一个非常basic approach ,根据您的喜好调整 colors、角等……:

import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    var body: some View {
        TextFormats()
    }
}

struct GrayButtonStyle: ButtonStyle {
    let w: CGFloat
    let h: CGFloat
    
    init(w: CGFloat, h: CGFloat) {
        self.w = w
        self.h = h
    }
    
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .foregroundColor(Color.white)
            .frame(width: w, height: h)
            .padding(5)
            .background(Color(UIColor.systemGray4))
            .overlay(Rectangle().strokeBorder(Color.gray, lineWidth: 1))
    }
}

struct TextFormats: View {
    let sx = CGFloat(20)
    let color = Color.black
    
    @State var bold = false
    @State var italic = false
    @State var underline = false
    
    var body: some View {
        HStack (spacing: 0) {
            Group {
                Button(action: { bold.toggle() }) {
                    Image(systemName: "bold").resizable().frame(width: sx, height: sx)
                        .foregroundColor(bold ? .blue : color)
                }
                Button(action: { italic.toggle() }) {
                    Image(systemName: "italic").resizable().frame(width: sx, height: sx)
                        .foregroundColor(italic ? .blue : color)
                }
                Button(action: { underline.toggle() }) {
                    Image(systemName: "underline").resizable().frame(width: sx, height: sx)
                        .foregroundColor(underline ? .blue : color)
                }
            }.buttonStyle(GrayButtonStyle(w: sx+5, h: sx+5))
        }.padding(1)
            .overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(.white, lineWidth: 2))
            .clipped(antialiased: true)
    }
    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM