Open

SwiftUIのあれこれ

8

animationに関するあれこれ。

・タップで変化

SwiftUI
 @State var show = false

変化させたい箇所の指定

SwiftUI
  .offset(x: 0, y: show ? -400 : -40)

速度などの調整

SwiftUI
.animation(.easeInOut(duration: 0.5))

トリガー

SwiftUI
  .onTapGesture {
                    self.show.toggle()
                }

細かい速度の設定

SwiftUI
 .animation(.timingCurve(0.2, 0.8, 0.2, 1, duration: 0.8))

下記サイトでcurveの作成→コピペで使用可能

https://cubic-bezier.com/#0,.68,1,.37

ジェスチャーアンカー

SwiftUI
 .gesture(
DragGesture()
.onChanged { value in
self.bottomState = value.translation
                         }
.onEnded {value in
      if self.bottomState.height > 50{
          self.showCard = false
                                        }
       if self.bottomState.height < -100{
           self.bottomState.height = -300
                                        } else {
                                self.bottomState = .zero
                            }
                       }
                   )

underCard

SwiftUI
 VStack {
                RoundedRectangle(cornerRadius: 3)
                    .frame(width: 40, height: 5, alignment: .center)
                    .opacity(0.1)
                Text("text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text ")
                    .multilineTextAlignment(.center)
                    .font(.subheadline)
                    .lineSpacing(4)
                Spacer()
            }
            .padding()
            .background(Color(.white))
            .cornerRadius(30)
            .shadow(radius: 20)
            .offset(x: 0, y: 500)

上記のものをジェスチャーで移動

SwiftUI
   @State var viewState = CGSize.zero
   
    var body: some View {
        VStack {
            RoundedRectangle(cornerRadius: 3)
                .frame(width: 40, height: 5, alignment: .center)
                .opacity(0.1)
            Text("text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text ")
                .multilineTextAlignment(.center)
                .font(.subheadline)
                .lineSpacing(4)
            Spacer()
        }
        .padding()
        .background(Color(.white))
        .cornerRadius(30)
        .shadow(radius: 20)
       
        .offset(x: 0, y: viewState.height + 500)

        .gesture(DragGesture()
                    .onChanged { value in
                        self.viewState = value.translation
                    }
                    .onEnded{ value in
                        self.viewState = .zero
                        
                    }
        )
    }
}

3DEffectを使ってアニメーション表示

SwiftUI
.rotation3DEffect(
                Angle(degrees: showProfile ? Double(viewState.height / 12) - 10 : 0),
                axis: (x: 10, y: 0, z: 0))

綺麗に見えるanimationの設定

SwiftUI
.animation(.spring(response: 0.5, dampingFraction: 0.6, blendDuration: 0))

3DAnimation(Viewを囲むように移動)

脳死で下記コピペでOK

SwiftUI
 .rotation3DEffect(
                                    Angle(degrees: Double(geometry.frame(in: .global).minX - 30) / -20
                                ), axis: (x: 0, y: 10, z: 0)
                                )

ダークモード無効

Info.plistにAppearanceを追加 → ValueにLight
でダークモード無効化

キー入力可視化

SwiftUI
import SwiftUI
struct SwiftUIView: View {
    @State private var text = ""
    @State private var flag = false
    var body: some View {
        let textFlag = String(flag)
        VStack {
            TextField("サンプル", text: $text)
            Text("\(textFlag)")
        } .textFieldStyle(CustomTextFieldStyle())
        .onTapGesture {
            if flag == true{
                UIApplication.shared.closeKeyboard()
                flag = false
            }else {
                flag = true
            }
        }
    }
}

struct CustomTextFieldStyle: TextFieldStyle {
    func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
            .padding(.horizontal,16)
            .font(.system(size: 20))
            .frame(width: UIScreen.main.bounds.width * 1, height: 60)
            .background(Color.secondary)
            .cornerRadius(8)
            .foregroundColor(.white)
        
    }
}

extension UIApplication {
    func closeKeyboard() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

Colorに関するあれこれ

ColorLiteralの使用方法。

SwiftUI
Color( colorLiteral())

背景を一色にする(セーフエリア)

SwiftUI
 Color(.white)
                .edgesIgnoringSafeArea(.all)

スクロールの作り方

SwiftUI
ScrollView(.horizontal) {
                HStack(spacing: 30) {
                    ForEach(0 ..< 5) { item in
                     RoundedRectangle(cornerRadius: 30)
                    .frame(width: 300, height: 300)
                       }
                }
                .padding(30)
                .padding(.bottom, 30)
            }

LazyHGridを使用したもの

SwiftUI
struct SclrollSampler: View {
    let data = 1...10
    let rows = [GridItem(.fixed(200))]
    var body: some View {
        
        ScrollView(.horizontal) {
            LazyHGrid(rows: rows) {
                ForEach(data, id: \.self) { item in
                    
                    VStack {
                        Image("SwiftUI")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: UIScreen.main.bounds.width * 1, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                        Text("Lesson\(item)")
                    }
                    
                }
            }
        }
    }
}

Sectionを使用してDataにして表示する

SwiftUI
 ScrollView(.horizontal) {
                HStack(spacing: 30) {
                    ForEach(sectionData) { item in
                        SectionView(section: item)
                    }
                }
                .padding(30)
                .padding(.bottom, 30)
            }

SectionViewを作る

SwiftUI
 struct SectionView: View {
    var section: Section
    var body: some View {
        VStack {
            HStack {
                Text(section.title)
                    .font(.system(size: 28, weight: .bold, design: .default))
                    .frame(width: 160, alignment: .leading)
                    .foregroundColor(.white)
                Spacer()
                Image(section.lodo)
                    .resizable()
                    .frame(width: 50, height: 50)
            }
            Text(section.text.uppercased())
                .frame(maxWidth: .infinity, alignment: .leading)
            
            section.image
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 210)
        }
        .padding(.top, 20)
        .padding(.horizontal, 20)
        .frame(width: 275, height: 275)
        .background(section.color)
        .cornerRadius(30)
        .shadow(color: section.color.opacity(0.3), radius: 20, x: 0, y: 20)
    }
}

struct Section: Identifiable {
    var id = UUID()
    var title: String
    var text: String
    var lodo: String
    var image: Image
    var color: Color
}

let sectionData = [
    Section(title: "Lesson1 SwiftUI Layout", text: "10 Corse", lodo: "Logo4", image: Image(uiImage:  imageLiteral(resourceName: "5")), color: Color( colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1))),
    Section(title: "Lesson2 SwiftUI Gesture", text: "6 Corse", lodo: "Logo4", image: Image(uiImage:  imageLiteral(resourceName: "2")), color: Color( colorLiteral(red: 0.8549019694, green: 0.250980407, blue: 0.4784313738, alpha: 1))),
    Section(title: "Lesson3 SwiftUI Amimation", text: "8 Corse", lodo: "Logo4", image: Image(uiImage:  imageLiteral(resourceName: "6")), color: Color( colorLiteral(red: 0.9411764741, green: 0.4980392158, blue: 0.3529411852, alpha: 1))),
    Section(title: "Lesson3 SwiftUI Binding", text: "4 Corse", lodo: "Logo4", image: Image(uiImage:  imageLiteral(resourceName: "7")), color: Color( colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1)))
    
]

テキストに関するあれこれ

全角
Text("hogehoge".uppercased())
サイズなど
.font(.system(size: 28, weight: .bold, design: .default))

fontのデザインをカスタムする

・google fontから好きなフォントをDL
・info.plistで設定
→Fonts provided by applicationを追加
 valueにフォント名.ttf を記入
・ .font(.custom(“フォント名”, fixedSize: 16))

小数点以下の表示する色んな方法

let formatText = String(format: "%.0f", myDouble * 100)

DoubleをFGFloatに変換する方法

@State var myDouble: Double = 0.9

let myFloat = NSNumber.init(value: myDouble).floatValue
let myCGFloat = CGFloat(myFloat)

intを使用したもの

Text("(Int(percent))%")

Geometryの使い方

SwiftUI
GeometryReader { geometry in
                            SectionView(section: item)
                        }
                        .frame(width: 275, height: 275)

ステータスバーの表示、非表示

SwiftUI
 .statusBar(hidden: false)
ログインするとコメントできます