๐Ÿ”นview.clipShape()

โ•ฑ๐Ÿšง under construction

SwiftUI โŸฉ view โŸฉ modifier โŸฉ rendering โŸฉ .clipShape()

่ฃๆŽ‰ view ๅœจๆŒ‡ๅฎš shape ๅค–้ข็š„้ƒจๅˆ†ใ€‚

โญ๏ธ ๆณจๆ„๏ผš.clipShape() ไธๆœƒๆ”น่ฎŠ frameโ—

๐Ÿ‘‰ mismatching types ๐Ÿ‘‰ AnyShape๏ผš่ฃก้ขๆœ‰ MyAnyShape (custom type erasure) ็š„ๅฎš็พฉ ๐Ÿ‘‰ has non-Sendable type๏ผš่ฃก้ขๆœ‰ MyShape (custom enum) ็š„ๅฎš็พฉ

import SwiftUI

struct TempView: View {
    
    @State var isOn = false
    
    private let size: CGFloat = 20
    
    var body: some View {
        VStack {
            text
            Toggle("ๅˆ‡ๆ›", isOn: $isOn)
                .padding()
        }
        
    }
    
    // โญ๏ธ ๆณจๆ„๏ผš
    //    ้€™่ฃ็”จไบ†ไธ‰ๅ€‹ๆ–นๆกˆ๏ผŒไธ‰ๅ€‹็š„ๅ›žๅ‚ณๅž‹ๅˆฅ้ƒฝไธๅŒ(AnyShape, MyShape, MyAnyShape)๏ผŒ 
    //    ๆ‰€ไปฅ return type ๅฟ…้ ˆ็”จ `some Shape`๏ผŒ่ฎ“ compiler ่‡ช่กŒๅˆคๆ–ทใ€‚
    private var dynamicShape: some Shape {
        
        // โญ๏ธ ๆ–นๆกˆไธ€๏ผšไฝฟ็”จ AnyShape (official type erasure)
//        isOn ? AnyShape(circle) : AnyShape(roundedRect)
        
        // โญ๏ธ ๆ–นๆกˆไบŒ๏ผšไฝฟ็”จ MyShape (custom enum)
//        isOn ? MyShape.circle : MyShape.roundedRect(
//            cornerSize: CGSize(width: size, height: size)
//        )
        
        // โญ๏ธ ๆ–นๆกˆไธ‰๏ผšไฝฟ็”จ MyAnyShape (custom type erasure)
        isOn ? MyAnyShape(circle) : MyAnyShape(roundedRect)
    }
    
    private var text: some View {
        Text("Clipped text in a circle")
            .frame(width: 175, height: 100)
            .foregroundColor(Color.white)
            .background(Color.blue)
            
            // ------------------------------------------------
            // โญ๏ธ ่‹ฅไฝฟ็”จๅ‹•ๆ…‹ๅฝข็‹€ๆ™‚๏ผŒๅฟ…้ ˆๆƒณ่พฆๆณ•ๆถˆ้™คไธๅŒๅฝข็‹€็š„ๅž‹ๅˆฅๅ•้กŒ
            .clipShape(dynamicShape)
            
            // ๐Ÿž ไธ‹้ข็š„ๅฏซๆณ•ๆœƒ็”ข็”Ÿ "mismatching types" ็š„้Œฏ่ชค
            .clipShape(isOn ? Circle() : Capsule())
            // ------------------------------------------------
            
            .animation(.default, value: isOn)
    }
    
    private var roundedRect: some Shape {
        RoundedRectangle(cornerSize: 
            CGSize(width: size, height: size)
        )
    }
    
    private var circle: some Shape {
        Circle()
    }
}

Last updated