SwiftUI 的 UI 元件 & data binding-脫離麻瓜身份學咒語!!!

chinger
海大 SwiftUI iOS / Flutter App 程式設計
6 min readJun 3, 2020

(一)App操作影片&Gif

(二)Github連結

https://github.com/Chinger-Chang/HW3

(三)特製的 App 畫面截圖

(四)文字說明

花了點時間想主題,最後決定繼續進行延用我最愛的哈利波特!!!感謝維基百科幫我整理好了,不然我可能為了咒語找資料找半天😂,一開始前面是結合需要的基本功能做出屬於自己客製化的霍格華茲學生證,之後想學咒語的意願必須超過50%才會顯示你想學哪集的咒語,本來想做個小遊戲,但沒時間就放棄了。對了,data那邊還有些不太懂,導致SpellDetailView那為了判斷及顯示每一集的咒語用最笨的方式寫了一堆一樣的東西,不知如何簡化😣。

(五)重點程式碼說明

  1. ContextMenu
Text("\(episode2[index].name)\n\(episode2[index].description)")
.multilineTextAlignment(.center)
.font(Font.custom("Copperplate-Bold", size: 25))
.foregroundColor(Color(red: 77/255, green: 77/255, blue: 255/255))
.padding()
.background(Color(red: 184/255, green: 184/255, blue: 255/255))
.cornerRadius(20)
.padding(8)
.overlay(RoundedRectangle(cornerRadius: 20)
.stroke(Color(red: 112/255, green: 0/255, blue: 209/255),lineWidth: 5))
.padding()
.contextMenu {
Button(action: {}) {
Text("收藏")
Image(systemName: "star.fill")
}
}

2.音樂音效

import SwiftUI
import AVFoundation
import MediaPlayer
struct MusicView: View {
@State var play = true

let player = AVPlayer()
let commandCenter = MPRemoteCommandCenter.shared()
var body: some View {
HStack{
Text("Harry's Wondrous World ")
.font(Font.custom("Baskerville-Bold", size: 23))
.bold()
.foregroundColor(Color(red: 0/255, green: 0/255, blue: 139/255))

Spacer()
Button(action: {
let fileUrl=Bundle.main.url(forResource:"HarrysWorld",withExtension: "mp3")
let playerItem = AVPlayerItem(url: fileUrl!)
self.player.replaceCurrentItem(with: playerItem)
self.play.toggle()
if self.play{
self.player.pause()
}
else{
self.player.play()
}
self.commandCenter.playCommand.addTarget { event in
if self.player.rate == 0.0 {
self.player.play()
return .success
}
return .commandFailed
}

self.commandCenter.pauseCommand.addTarget { event in
if self.player.rate == 1.0 {
self.player.pause()
return .success
}
return .commandFailed
}

}){
Image(systemName: play ? "play.circle" : "pause.circle")
.resizable()
.frame(width:30,height:30)
.foregroundColor(Color(red: 105/255, green: 89/255, blue: 205/255))
}
}
.padding(10)
.background(LinearGradient(gradient: Gradient(colors: [Color(red: 221/255, green: 160/255, blue: 221/255), Color(red: 138/255, green: 43/255, blue: 226/255)]), startPoint: UnitPoint(x: 0.4, y: 0.4), endPoint: UnitPoint(x: 0.4, y: 1)))
.cornerRadius(50)
}
}

--

--