Advertisement
Milotronik

CardView Size Kingfisher

Mar 15th, 2025 (edited)
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.08 KB | None | 0 0
  1. import SwiftUI
  2. import Kingfisher
  3.  
  4. enum CardSize {
  5.     case small
  6.     case large
  7. }
  8.  
  9. struct CardView: View {
  10.     let imageURL: URL?
  11.     private let smallSize: CGFloat = 210
  12.     @Binding var cardSize: CardSize // Binding to allow external control
  13.  
  14.     var body: some View {
  15.         let cardWidth = cardSize == .small ? smallSize : UIScreen.main.bounds.width - 32
  16.         let cardHeight = cardWidth.aspectRatioHeight
  17.  
  18.         VStack {
  19.             KFImage(imageURL)
  20.                 .resizable()
  21.                 .aspectRatio(contentMode: .fill)
  22.                 .frame(width: cardWidth - 16, height: cardHeight - 16) // Inner padding simulation
  23.                 .clipped()
  24.                 .cornerRadius(10)
  25.         }
  26.         .frame(width: cardWidth, height: cardHeight) // Card dimensions based on image size
  27.         .background(Color.white) // Background color for the card
  28.         .cornerRadius(12) // Corner radius for the entire card
  29.         .overlay(
  30.             RoundedRectangle(cornerRadius: 12) // Border for the card
  31.                 .stroke(Color.black, lineWidth: 2)
  32.         )
  33.         .padding(8) // Outer padding around the card
  34.     }
  35. }
  36.  
  37. extension CGFloat {
  38.     var aspectRatioHeight: CGFloat {
  39.         self / 16 * 9
  40.     }
  41. }
  42.  
  43. struct ContentView: View {
  44.     @State private var cardSize: CardSize = .small // State variable to track size
  45.  
  46.     var body: some View {
  47.         VStack {
  48.             // Pass the binding to CardView
  49.             CardView(imageURL: URL(string: "https://i.postimg.cc/GHLSWpkp/Travel-test-03.png"), cardSize: $cardSize)
  50.                 .padding()
  51.  
  52.             Button(action: {
  53.                 // Toggle between small and large sizes by assigning a new value
  54.                 cardSize = (cardSize == .small ? .large : .small)
  55.             }) {
  56.                 Text(cardSize == .small ? "Make Large" : "Make Small")
  57.                     .padding()
  58.                     .background(Color.blue)
  59.                     .foregroundColor(.white)
  60.                     .cornerRadius(8)
  61.             }
  62.         }
  63.     }
  64. }
  65.  
  66. #Preview {
  67.     ContentView()
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement