2022年9月

ObservableObj


import SwiftUI
import SpriteKit


class GameScene: SKScene, SKPhysicsContactDelegate, ObservableObject {  // <<: Here 1
  //  @Published var updates = 0
    @Published var gameScore = 0 // <<: Here 2
    @Published var lenght: CGFloat = 1
          var up: Bool = false

  //  let removeLabel = SKAction.sequence([SKAction.fadeIn(withDuration: 0.3), SKAction.wait(forDuration: 0.8), SKAction.fadeOut(withDuration: 0.3)])
    let tball = SKShapeNode(circleOfRadius: 20)
    
    var lastUpdateTime2 : TimeInterval = 0  
    override func didMove(to view: SKView) {
        backgroundColor = .yellow
        physicsBody = SKPhysicsBody(edgeLoopFrom: frame)        
        tball.position = CGPoint(x: 0, y: 0)
             tball.fillColor = .blue
             self.addChild(tball)
     //   tball.zPosition = 10
    }    
    func change(){
       if self.lenght > 100 {
              up = false
         }else if (self.lenght < 10){
               up = true
       }
            up ? (self.lenght += 1) : (self.lenght -= 1)
       }
override func update(_ currentTime: TimeInterval) {
      //   self.change()
  if lastUpdateTime2 == 0 {
        lastUpdateTime2 = currentTime
     }
    if currentTime - lastUpdateTime2 > 1 - 0.9 {
       self.change()
       lastUpdateTime2 = currentTime
        }
           }
    /*
    func ball() {
   let ball = SKShapeNode(circleOfRadius: 20)
    let MinValue = self.size.width / 8
   let MaxValue = self.size.width  - 50
    let SpawnPoint = UInt32(MaxValue - MinValue)
   ball.position = CGPoint(x: CGFloat(arc4random_uniform(SpawnPoint)), y: 200)
      ball.fillColor = .blue
      self.addChild(ball)
    }
     */
 func ball() {
      let moveDown = SKAction.moveTo(x:130, duration: 2.5)
      let moveUp = SKAction.moveTo(x: -130, duration: 2.5)
      let actionSequence2 = SKAction.sequence([moveDown, moveUp])
      let moveRepeat = SKAction.repeatForever(actionSequence2)
    tball.run(moveRepeat, withKey: "moveX")
    }
 func ball2() {
    let moveDown2 = SKAction.moveTo(x:130, duration: -2.5)
    let moveUp2 = SKAction.moveTo(x: -130, duration: -2.5)
    let actionSequence3 = SKAction.sequence([moveDown2, moveUp2])
    let moveRepeat2 = SKAction.repeatForever(actionSequence3)
    tball.run(moveRepeat2, withKey: "moveX2")
    }
    func addScore(){
        if gameScore < 10 {
            gameScore += 1            
        } else {
            gameScore += 5            
        }
    }    
}
struct ContentView: View {
    @State var flag = true
    @State var showingSheet : Bool = false
 //   @StateObject var gameScene = GameScene() // <<: Here 3
 /*
    let scene: GameScene = {
     let scene = GameScene()
     scene.size = CGSize(width: 300, height: 300)
     scene.scaleMode = .fill
     return scene
 }()
*/
@StateObject private var scene: GameScene = {
    let scene = GameScene()
     scene.size = CGSize(width: 300, height: 300)
     scene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
      scene.scaleMode = .fill
       return scene
  }()           
    var body: some View {
        Spacer()
        VStack {
        Button(action: {
            if(self.flag){
             scene.ball()
             self.flag = false
          }
           else{
              scene.ball2()
             self.flag = true
           }
           }
        ){
          Text("ball start on off")
             .font(.title3)
              .foregroundColor(Color.purple)
               .padding(.bottom, 20)
  }
       Button(
           action: { showingSheet = true },
            label: {
           Text("ShowSheet")
          })
        .sheet(isPresented: $showingSheet){
         SecondSheet()
          }
 }
     ZStack {
         SpriteView(scene: scene)
             .frame(width: 300, height: 300)
             .ignoresSafeArea()
        Circle().frame(width: scene.lenght, height: scene.lenght)
            .foregroundColor(.green)
              .padding(.top, 150)
   
        Button(action: {
          scene.addScore()
            }) {
             Text("Score: \(scene.gameScore)")
              .font(.title3)
               .frame(width: 110, height: 30, alignment: .center)
                .foregroundColor(Color.white)
                .background(Color.pink)
                 .cornerRadius(5, antialiased: true)
                 .padding(.bottom, 130)
      }
     }
     .padding(.bottom, 110)       
    }    
}
struct SecondSheet: View {
    @Environment(\.dismiss) var dismiss
     var body: some View {
         VStack{
   Text("SecondSheet")
       .fontWeight(.heavy)
       .font(.title)
   Button("画面を閉じる") {
     dismiss()
     }
     }
 }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

SideMenu


import SwiftUI


struct ContentView: View {
    @State var showHamburgerMenu = false
    var body: some View {

let drag = DragGesture()
   .onEnded {
    if $0.translation.width < -100 {
   withAnimation {
     self.showHamburgerMenu = false
        }
  }
}
        
NavigationView {
GeometryReader { geometry in
    ZStack(alignment: .leading) {
  MainView(showHamburgerMenu: self.$showHamburgerMenu)
  .frame(width: geometry.size.width, height: geometry.size.height)
   .offset(x: self.showHamburgerMenu ? geometry.size.width/2 : 0)
   .disabled(self.showHamburgerMenu ? true : false)
      if self.showHamburgerMenu {
         SideMenuView(isOpen: $showHamburgerMenu)
         .frame(width: geometry.size.width)
          //    .frame(width: geometry.size.width/2)
           .transition(.move(edge: .leading))
       }
  }
.gesture(drag)
  }
   .navigationTitle("← Menu")
   .navigationBarTitleDisplayMode(.inline)
   .navigationBarItems(leading: (
       Button(action: {
        withAnimation {
           self.showHamburgerMenu.toggle()
  }
  }) {
    //    Image(systemName: "line.horizontal.3")
    Image(systemName: showHamburgerMenu ? "xmark" : "line.horizontal.3")
     //  .imageScale(.large)
        .font(.title2)
        .foregroundColor(.red)
         }
   ))
 }  
    }
}

struct MainView: View {
    @Binding var showHamburgerMenu: Bool
    @State var isShowSubViw = false
    var body: some View {
    ZStack{
      Color.yellow
       .frame(maxWidth: .infinity, maxHeight: .infinity)
        .ignoresSafeArea()
        ScrollView(.horizontal, showsIndicators: false) {

 HStack{
  GeometryReader { geometry in
     ImageCarouselView(numberOfImages: 1) {
      //    Text("Bananas 🐻🐻")
      Image(decorative: "d01")
        .resizable()
        .scaledToFit()
        .frame(maxWidth: 80, maxHeight: 80, alignment: .center)
        .clipShape(Circle())
       }
    }.frame(width: 383, height: 240)
        GeometryReader { geometry in
      ImageCarouselView(numberOfImages: 1) {
       Text("Peaches 🍑🍑")            
   }
 }.frame(width: 380, height: 240)
      GeometryReader { geometry in
     ImageCarouselView(numberOfImages: 1) {
  Text("Apples 🍏🍏")
    }
    }.frame(width: 380, height: 240)
      GeometryReader { geometry in
      ImageCarouselView(numberOfImages: 1) {
       Text("inuwan 🐶🐶")
     }
   }.frame(width: 382, height: 240)
      GeometryReader { geometry in
     ImageCarouselView(numberOfImages: 1) {
      //        Text("sakana 🐟🐟")
        Image(decorative: "d04")
        .resizable()
       .scaledToFit()
       .frame(maxWidth: 80, maxHeight: 80, alignment: .center)
       .clipShape(Circle())
    }
   }.frame(width: 388, height: 240)
 }.padding(.leading)
 }
 .foregroundColor(Color.white)
  //    .background(Color.yellow)
 }
  GeometryReader { geometory in
   ZStack {
   if isShowSubViw {
       SubView()
         } else {
           Button(action: {
           withAnimation() {
             self.isShowSubViw.toggle()
     }
      }) {
      Text("SubViewへ")
   }
    .padding(.top, 100)
       VStack {
        Text("MainView")
         .font(.system(size: 35, weight: .black, design: .default))
          .padding(.top, 50)
    }
  }
 }
 .frame(width: geometory.size.width,
    height: geometory.size.height)
   //   .background(Color.yellow)
    .animation(.easeInOut(duration: 0.42))
  }
.transition(.move(edge: .leading))
 }
}

struct SubView: View {
 @State var isShowSubViw = false
    let imageUrl = URL(string: "https://kyou.gif.jp/img/d07.jpg")
    var body: some View {
  ZStack{
      LinearGradient(gradient: Gradient(colors:  [Color.yellow, Color.green]), startPoint: .init(x: 0.3, y: 0.3), endPoint: .init(x: 0.55, y: 0.55))
      .frame(maxWidth: .infinity, maxHeight: .infinity)
      .ignoresSafeArea()        
    VStack{
        AsyncImage(url: imageUrl) { image in
         image.resizable()
       .aspectRatio(contentMode: .fill)
        .clipShape(Circle())
       } placeholder: {
          ProgressView()
 }
  .frame(width: 80, height: 80, alignment: .center)
    .padding(.bottom, 50)
     .padding(.trailing, 5)
//     .mask(RoundedRectangle(cornerRadius: 10))
  }
  GeometryReader { geometory in
     ZStack {
      if isShowSubViw {
      MainView(showHamburgerMenu: $isShowSubViw)
        } else {
       Button(action: {
           withAnimation() {
         self.isShowSubViw.toggle()
  }
  }) {
   Text("MainViewへ")
   }
  .padding(.top, 100)
   VStack {
      Text("SubView")
      .font(.system(size: 35, weight: .black, design: .default))
        .padding(.top, 50)
  }
  }
 }
  .frame(width: geometory.size.width,
     height: geometory.size.height)
   //  .background(Color.green)
    //   .background(
       //   gradient: Gradient(colors: [Color.yellow, Color.green]),
       //   startPoint: .init(x: 0.3, y: 0.3),    // start地点
      //   endPoint: .init(x: 0.55, y: 0.55)     // end地点  
       //    ))
      .animation(.easeInOut(duration: 0.42))
 }
.transition(.move(edge: .leading))
     }
  }
}

struct SideMenuView: View {
    @Binding var isOpen: Bool
    let width: CGFloat = 280
    var body: some View {
ZStack {
      GeometryReader { geometry in
           EmptyView()
   }
       .background(Color.gray.opacity(0.3))
       .opacity(self.isOpen ? 1.0 : 0.0)
         .opacity(1.0)
        .animation(.easeIn(duration: 0.25))
         .onTapGesture {
         self.isOpen = false
  }          
  VStack(alignment: .leading) {
    HStack {
      Image(systemName: "person")
        .foregroundColor(.white)
        .imageScale(.large)
 NavigationLink(destination: ProfileView()) {
       Text("Profile")
        .foregroundColor(.white)
         .font(.headline)
       }
 }
   .padding(.top, 80)
HStack {
     Image(systemName: "envelope")
     .foregroundColor(.white)
      .imageScale(.large)
    NavigationLink(destination: MessagesView()) {
       Text("Messages")
        .foregroundColor(.white)
        .font(.headline)
         }
    }
     .padding(.top, 30)
       HStack {
        Image(systemName: "gear")
            .foregroundColor(.white)
            .imageScale(.large)
      NavigationLink(destination: SettingsView()) {
            Text("Settings")
            .foregroundColor(.white)
            .font(.headline)
         }
   }
   .padding(.top, 30)
     HStack {
        Image(systemName: "pencil.circle")
         .foregroundColor(.white)
        .imageScale(.large)
       NavigationLink(destination: PencilView()) {
           Text("Pencil test")
           .foregroundColor(.white)
             .font(.headline)
           }
       }
       .padding(.top, 30)
         Spacer()
   }
     //   .padding()
     //   .frame(maxWidth: .infinity, alignment: .leading)
     //   .background(Color(red: 132/255, green: 132/255, blue: 132/255))
     //   .edgesIgnoringSafeArea(.all)
     .frame(width: width)
      //  .background(Color(UIColor.systemGray6))
        .background(Color.gray)
       .offset(x: self.isOpen ? 0 : -self.width)
     .animation(.easeIn(duration: 0.25))
     //   .padding(.top, 100)
     .padding(.leading, -100)
    Spacer()
 }
 }
}

struct PencilView: View {
    var body: some View {
 ZStack{
   Color.purple
   .frame(maxWidth: .infinity, maxHeight: .infinity)
   .ignoresSafeArea()
   VStack{
     Text("PencilView Subview")
      Text("MyPencilView")
       .font(.title)
  }
  .navigationTitle("PencilView")
    .navigationBarBackButtonHidden(true)
     .toolbar {
      ToolbarItem(placement: .navigationBarLeading) {
     NavigationBackItem(title: "Menuへ戻る")
   }
   }
  }
    }
}

struct SettingsView: View {
    var body: some View {
    ZStack{
       Color.yellow
       .frame(maxWidth: .infinity, maxHeight: .infinity)
      .ignoresSafeArea()
   VStack{
      Text("Settings Subview")
      Text("MySubview")
       .font(.title)          
 }
  .navigationTitle("SettingsView")
     .navigationBarBackButtonHidden(true)
     .toolbar {
       ToolbarItem(placement: .navigationBarLeading) {
        NavigationBackItem(title: "Menuへ戻る")
          }
        }
      }
  }
}

struct MessagesView: View {
    var body: some View {
        ZStack{
        Color.green
        .frame(maxWidth: .infinity, maxHeight: .infinity)
         .ignoresSafeArea()
   VStack{
       Text("Messages Subview")
}
   .navigationTitle("MessagesView")
    .navigationBarBackButtonHidden(true)
      .toolbar {
       ToolbarItem(placement: .navigationBarLeading) {
        NavigationBackItem(title: "Menuへ戻る")
          }
      }
  }
    }
}

struct ProfileView: View {
    init(){
      //List全体の背景色の設定
       UITableView.appearance().backgroundColor = UIColor.white
      }
@State private var isNextPresented = false
    var body: some View {
      ZStack{
        Color.orange
       .frame(maxWidth: .infinity, maxHeight: .infinity)
        .ignoresSafeArea()
  NavigationView {
      VStack{
     Text("Profile Subview")
        .font(.title)
    List {
      NavigationLink("ChildViewへ")  {
        ChildView()
   }.listRowBackground(Color.gray.opacity(0.2))
     }
 }           
 }
 //  .navigationTitle("ProfileView")
     .navigationBarBackButtonHidden(true)
     .toolbar {
      ToolbarItem(placement: .navigationBarLeading) {
     NavigationBackItem(title: "Menuへ戻る")
    }
     ToolbarItem(placement: .navigationBarTrailing){
      Button {
            isNextPresented.toggle()
            } label: {
          HStack {
          Text("Next")
           Image(systemName: "person.fill")
           }
     }
    .fullScreenCover(isPresented: $isNextPresented) {
         NextView()
      }
    }
    }
     }
    }
}

struct ChildView: View {
    @Environment(\.dismiss) var dismiss   
var body: some View {
     VStack {
     Text("ChildView")
      .font(.title)
   }
   .navigationBarBackButtonHidden(true)
      Button(action: {
        dismiss()
      }, label: {
      Text("Profile Subviewへ")
        })
    }
}

struct NextView: View {
    @Environment(\.dismiss) private var dismiss
    var body: some View {
        VStack(spacing: 32) {
          Text("Hello,NextView")
            .font(.title)
       Button {
         dismiss()
      } label: {
        HStack {
        Text("Nextへ")
         Image(systemName: "chevron.up")
        .resizable()
         .frame(width: 30, height: 20)
     }  
      }
        }
    }
}

struct NavigationBackItem: View {
    @Environment(\.dismiss) private var dismissOn
    var title : String = ""
    var body: some View {
        Button {
          dismissOn()
     } label: {
      HStack {
       Image(systemName: "lessthan")
        .foregroundColor(.blue)
        .padding(.leading, -4.0)
         Text(title)
        .foregroundColor(Color.blue)
        .padding(.leading, -7.0)
      }
   }
 }
}

struct ImageCarouselView: View {
    private var numberOfImages: Int
    private var content: Content
    @State private var currentIndex: Int = 0
    private let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()

    init(numberOfImages: Int, @ViewBuilder content: () -> Content) {
        self.numberOfImages = numberOfImages
        self.content = content()
    }
 var body: some View {
     GeometryReader { geometry in
     HStack(spacing: 0) {
       self.content
 }
      .frame(width: geometry.size.width - 50, height: geometry.size.height - 50, alignment: .center)
      .offset(x: CGFloat(self.currentIndex) * -geometry.size.width, y: 0)
      .animation(.spring())
       .onReceive(self.timer) { _ in
         self.currentIndex = (self.currentIndex + 1) % 5
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

TabScroll




import SwiftUI

struct ContentView: View {
    @State var selectedTag = 1

var body: some View {
  TabView(selection: $selectedTag) {
  HomeTabView().tag(1)
   WeatherTabView().tag(2)
   NewsTabView().tag(3)
    NewsTabView2().tag(4)
     NewsTabView3().tag(5)
 }
    .tabViewStyle(PageTabViewStyle())
    .ignoresSafeArea()
  }
}

struct HomeTabView: View {
   var body: some View {
     VStack {
      Image(systemName: "music.note.house")
        .scaleEffect(x: 3.0, y: 3.0)
       .frame(width: 100, height: 100)
    Text("HOME").font(.system(size: 40))
 }
     .frame(maxWidth: .infinity, maxHeight: .infinity)
     .background(Color(red: 0.5, green: 0.9, blue: 0.9))
    .ignoresSafeArea()
 }
}

struct WeatherTabView: View {
    var body: some View {
      VStack {
         Image(systemName: "cloud.sun")
          .scaleEffect(x: 3.0, y: 3.0)
           .frame(width: 100, height: 100)
          Text("Weather").font(.system(size: 40))
 }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .background(Color(red: 1.0, green: 0.9, blue: 1.0))
    .ignoresSafeArea()
   }
}

struct NewsTabView: View {
var body: some View {
     VStack {
        Image(systemName: "newspaper")
        .scaleEffect(x: 3.0, y: 3.0)
         .frame(width: 100, height: 100)
       Text("News").font(.system(size: 40))
 }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .background(Color(red: 0.9, green: 0.9, blue: 0.8))
    .ignoresSafeArea()
 }
}

struct NewsTabView2: View {
  @State var isShowSubViw = false
    var body: some View {
       GeometryReader { geometory in
     ZStack {
        VStack {
        Image(systemName: "ant.circle.fill")
         .scaleEffect(x: 3.0, y: 3.0)
         .frame(width: 100, height: 100)
          Text("NewsTabView2")
          .font(.system(size: 40, weight: .black, design: .default))
         .padding(.top, -20)
 }
   if isShowSubViw {
          SubView()
      } else {
         Button(action: {
         withAnimation() {
          self.isShowSubViw.toggle()
      }
}) {
     Text("SubViewへ遷移")
         .padding(.top, 200)
         }
       }
  }
      .frame(width: geometory.size.width,
        height: geometory.size.height)
         .background(Color.green)
          .animation(.easeInOut(duration: 0.42))
      }
       .transition(.move(edge: .leading))
  }
 }

struct SubView: View {
  @State var isShowSubViw = false
    var body: some View {
      GeometryReader { geometory in
       ZStack {
        if isShowSubViw {
            NewsTabView2()
        } else {
            Button(action: {
            withAnimation() {
             self.isShowSubViw.toggle()
         }
     }) {
      Text("NewsTabView2へ戻る")
       }
   .padding(.top, 100)
        VStack {
        Text("SubView")
       .font(.system(size: 40, weight: .black, design: .default))
 }
  }
    .frame(width: geometory.size.width,
       height: geometory.size.height)
    .background(
       LinearGradient(
      gradient: Gradient(colors: [Color.yellow, Color.red]),
       startPoint: .init(x: 0.3, y: 0.3),    // start地点
      endPoint: .init(x: 0.55, y: 0.55)     // end地点 。
 ))
   .animation(.easeInOut(duration: 0.42))
 }
   .transition(.move(edge: .leading))
}
}

struct NewsTabView3: View {
    @State var isShow: Bool = false
    var body: some View {
     VStack {
       Image(systemName: "ladybug.fill")
         .scaleEffect(x: 3.0, y: 3.0)
         .frame(width: 100, height: 100)
 Text("First View").font(.system(size: 30))
     .padding(.bottom, 30)
      Button(action: {
     withAnimation {
       self.isShow.toggle()
 }
  }) {
   Text("Second View pageへ").font(.system(size: 20))
 }
   .fullScreenCover(isPresented: $isShow){
    SomeView(isPresented: $isShow)  // SomeViewビューを表示する
   }
 }
 .frame(maxWidth: .infinity, maxHeight: .infinity)
 .background(Color.yellow)
  .ignoresSafeArea()
 }
}

struct SomeView: View {
    // ContentViewビューの変数isShowとバインディングする
    @Binding var isPresented: Bool
 var body: some View {
    NavigationView {
    VStack {
         Image(systemName: "ladybug").scaleEffect(2.0)
        Text("Second View").font(.title2).padding()
   }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
.background(
       LinearGradient(
         gradient: Gradient(colors: [Color.yellow, Color.green]),
          startPoint: .init(x: 0.3, y: 0.3),    // start地点
           endPoint: .init(x: 0.55, y: 0.55)     // end地点
      ))
.toolbar {
   ToolbarItem(placement: .navigationBarLeading) {
     Button {
       isPresented = false
  } label: {
     HStack {
         Image(systemName:"lessthan")
          .foregroundColor(.green)
          Text("First Viewへ戻る")
          .foregroundColor(Color.green)
      }
   }
  }
  }
  }
 }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Text


import SwiftUI


extension Text {
 func textModifier(color: Color) -> some View {
    self
    .font(.system(size: 14, design: .monospaced))
    .fontWeight(.bold) // Viewに準拠していないModifier
     .multilineTextAlignment(.center) // Viewに準拠していないModifier
     .padding(7)
    .overlay(RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 1))
    .foregroundColor(color)
  }
}

struct ContentView: View {
    let pi = 3.141519   // 円周率z
@State private var text: String = """
       A text editor view allows you to display and edit multiline,scrollable text in your app’s user interface.
       複数行のスクロール可能なテキストを表示・編集できる
       """

var body: some View {
   VStack {
 Text("myテキスト")
    .textModifier(color: .red)
Text("円周率:\(pi, specifier: "%.2f")")
   .font(.system(size: 40, weight: .black, design: .default))
   .foregroundColor(.green)
   .padding(.top, 10)

TextEditor(text: $text)
 .frame(width: 320, height: 150)
 .padding(.bottom, -20)

 Text("Hello, world!").kerning(5)
 .font(.custom("Times-Roman", size: 35))
 .padding(.top, 20)
  Text("エリア 200 x 200 の中に文章を中央寄りで表示します。よろしくお願いいたします。")
   .frame(width: 280, height: 100, alignment: .leading)
   .multilineTextAlignment(.leading)
   .lineSpacing(10)
 Text("SwiftUI")
 .font(.system(size: 50, weight: .black, design: .default))
 Divider().padding(.bottom, 10)
    Text("SwiftUIで") +
    Text("一部の文字").foregroundColor(.red).fontWeight(.bold) + Text("だけを装飾する。")
 }
 }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}