Skip to content

Instantly share code, notes, and snippets.

@creaaa
Created September 15, 2019 07:49
Show Gist options
  • Save creaaa/85e614053f5a3f953b5dd0dfad44344b to your computer and use it in GitHub Desktop.
Save creaaa/85e614053f5a3f953b5dd0dfad44344b to your computer and use it in GitHub Desktop.
最高
//
// ContentView.swift
// SwiftyPageControl
//
// Created by crea on 2019/09/15.
// Copyright © 2019 crea. All rights reserved.
//
import SwiftUI
enum PageControlError: Swift.Error {
case failedInitialization
}
struct ContentView: View {
@State var currentIndex = 0
@State var hidesForSinglePage = false
var body: some View {
try! PageControl(
numOfContents: 3,
currentPageColor: .blue,
tintColor: .green,
currentIndex: $currentIndex,
hidesForSinglePage: $hidesForSinglePage
)
}
}
struct PageControl: View {
let numOfContents: Int
let currentPageColor: Color
let tintColor: Color
@Binding var currentIndex: Int
@Binding var hidesForSinglePage: Bool
var shouldHide: Bool { numOfContents == 1 && hidesForSinglePage }
// @Stateは、プロパティ宣言で初期値を代入しておかないと、
// init内で参照できない = 代入できない。ふーん...?🤔
// と思いきや、もっと事態は悪い!
// @Stateの値に bodyの外からアクセスするとクラッシュするのだから。、
// initの目的・仕組み上、initで@Stateを初期化するのは無理!
// あくまで@Stateはローカル目的だ!
init(
numOfContents: Int,
currentPageColor: Color = .blue,
tintColor: Color = .red,
currentIndex: Binding<Int>,
hidesForSinglePage: Binding<Bool>
) throws {
guard currentIndex.wrappedValue + 1 <= numOfContents else {
throw PageControlError.failedInitialization
}
self.numOfContents = numOfContents
self.currentPageColor = currentPageColor
self.tintColor = tintColor
self._currentIndex = currentIndex
self._hidesForSinglePage = hidesForSinglePage
}
var body: some View {
HStack {
ForEach(0..<numOfContents, id: \.self) { index in
Circle()
.fill(index == self.currentIndex ? self.currentPageColor : self.tintColor)
.frame(width: 7, height: 7)
.onTapGesture {
self.currentIndex = index
}
}
}
.opacity(shouldHide ? 0 : 1)
}
}
struct PageControl_Previews: PreviewProvider {
// @Stateをstaticにしたら、.constantではないbindingを渡せるのでは?と思ったが、
// ビルドは通ったがプレビューがクラッシュする
static var previews: some View {
try! PageControl(numOfContents: 3,
currentPageColor: .yellow,
tintColor: .purple,
currentIndex: .constant(0),
hidesForSinglePage: .constant(false)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment