🌀view.overlayText()

⭐️

swiftcustomextensionView.overlayText()

在 view 上面放說明文字。可設定的參數:

  • text:說明文字

  • textColor:說明文字的顏色

  • borderColor:view 的邊框顏色

  • showContentBorder:要不要顯示 view 的邊框

// ⭐️ Dependencies:
// - view.if()

import SwiftUI

// (internal) view modifier
struct OverlayText: ViewModifier {
    
    var text: String = "untitled"        // text
    var textColor: Color = .primary      // text color
    var borderColor: Color = .secondary  // frame's border color
    var showContentBorder = false        // show border
          
    
    // body(content:) - ViewModifier requirement
    func body(content: Content) -> some View {

        content
            .if(showContentBorder) {
                $0.border(borderColor)
            }
            .overlay(
                Text("\(text)")
                    .multilineTextAlignment(.center)
                    .foregroundStyle(textColor)
                    .shadow(color: .black, radius: 3, x: 1, y: 1)
            )
            
    }
}

// ⭐️ public extension
public extension View {
 
    /// `view.overlayText("title")`
    func overlayText(
        _ text: String, 
        color: Color = .primary,
        showContentBorder show: Bool = false,
        borderColor: Color = .secondary
    ) -> some View { 
        modifier(OverlayText(text: text, textColor: color, borderColor: borderColor, showContentBorder: show)) 
    }
}

Last updated