欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[2]SwiftUI

程序员文章站 2024-03-24 12:41:34
...

将UIView转化为SwiftUIView

遵循UIViewRepresentable协议再完成makeUIView和updateUIView两个函数

struct MapView: UIViewRepresentable {
    
    func makeUIView(context: Context) -> MKMapView { MKMapView() }
    //给定一个View,根据updateUIView更新View

    func updateUIView(_ uiView: MKMapView, context: Context) { }
    //记录更新的视图
}

Image
自定义形状,显示的样式

Image(landmark.imageName)
    .resizable()
    .frame(width: 250,height: 250)
    .clipShape(Circle())//裁剪
    .overlay(Circle().stroke(Color.white,lineWidth: 4))//覆盖一个东西
    .shadow(radius: 10)
    .offset(x: 0, y: -130) //移动
    .padding(.bottom,-130)//offset和padding经常灵活使用

Button
显示的形式和action

Button(action: {
    self.userData.userLandmarks[self.landmarkIndex].isFavorite.toggle()
    }){
        if userData.userLandmarks[landmarkIndex].isFavorite {
       Image(systemName: "star.fill")
           .foregroundColor(.yellow)
      }else{
       Image(systemName:"star")
       .foregroundColor(.gray)
      }

ForEach和List

在list中加其他元素可以用ForEach将数据打包

List{
                
 Toggle(isOn: $showFavoritesOnly) {
      Text("只展示收藏")
  }
                
  //在list中加其他元素可以用ForEach将数据打包
 ForEach(userData.userLandmarks) { landmark in
    if !self.showFavoritesOnly || landmark.isFavorite{
        NavigationLink(
            destination: LandmarkDetail(landmark: landmark).environmentObject(self.userData)
                      ){
             LandmarkCell(landmark: landmark)
   		 }
    }

Preview

利用Group可以显示多个不同的数据

struct LandmarkCell_Previews: PreviewProvider {
    static var previews: some View {
        Group{
            LandmarkCell(landmark: landmarks[1])
            LandmarkCell(landmark: landmarks[2])
            LandmarkCell(landmark: landmarks[3])
            LandmarkCell(landmark: landmarks[4])
        }
        .previewLayout(.fixed(width: 300, height: 70))//显示的大小

    }
}

ObservableObject

//单个变量用@State一个数组用@EnvironmentObject

1.创建UserData类

import SwiftUI
import Combine

//单个变量用@State一个数组用ObservableObject
final class UserData: ObservableObject  {
    //当数据变化时发送更新后的数据给视图,视图就会刷新
    @Published var userLandmarks = landmarks
}

2.在页面生成前就实例化环境变量(SceneDelegate)

if let windowScene = scene as? UIWindowScene {
   let window = UIWindow(windowScene: windowScene)
   window.rootViewController = UIHostingController(rootView: contentView.environmentObject(UserData()))
   //在程序一开始就马上实例化环境变量
   self.window = window
   window.makeKeyAndVisible()
}

3.创建环境变量

    @EnvironmentObject var userData: UserData

4.确定的Index

var landmarkIndex: Int{
  	userData.userLandmarks.firstIndex(where: {$0.id == landmark.id})!
}
相关标签: iOS 开发