iPhoneの純正メッセージアプリをコピーして、SwiftUIの技術力向上をしていきます。
このような状態を目指していきます。
処理は後々追加していきます。
ここで受信したメッセージセルのデータを定義します。
struct Message: Identifiable, Codable {
var id: String
var name: String
var day: String
var lastMessage: String
init(id: String = "", name: String = "", day: String = "", lastMessage: String = "") {
self.id = id
self.name = name
self.day = day
self.lastMessage = lastMessage
}
var dictionary: [String:Any] {
return ["id": id,"name": name, "day": day, "lastMessage": lastMessage]
}
}
Messageで定義したデータを利用してセルを作成していきます。
struct MessageCell: View {
@Binding var message: Message
var body: some View {
HStack {
Image(systemName: "person.circle")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 40, height: 40)
.clipShape(Circle())
.padding()
VStack {
Divider()
HStack {
Text(message.name)
.frame(maxWidth: .infinity, alignment: .leading)
.bold()
Spacer()
Text(message.day)
.foregroundColor(.gray)
Image(systemName: "chevron.right")
.frame(width: 10, height: 10)
.foregroundColor(.gray)
.padding(.trailing, 15)
}
Text(message.lastMessage)
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundColor(.gray)
.lineLimit(2)
}
}
.frame(height: 70)
}
}
セルを追加した最終的なコードはこちらになります。
struct ContentView: View {
@State private var list: [Message] = [Message(id: "1", name: "テスト1", day: "2024/01/01", lastMessage: "テスト"),Message(id: "2", name: "テスト2", day: "2024/01/02", lastMessage: "テスト"),Message(id: "3", name: "テスト3", day: "2024/03/02", lastMessage: "テストテス")]
@State private var sheet = false
@State private var searchText = ""
@FocusState private var focus: Bool
var body: some View {
NavigationView {
ScrollView {
VStack {
ZStack{
TextField("検索", text: $searchText, onEditingChanged: { editing in
})
.background(.clear)
.frame(height: 40)
.padding(.leading, 30)
.padding(.trailing, 30)
HStack {
Image(systemName: "magnifyingglass")
.foregroundColor(.black)
.frame(width: 20, height: 20)
.padding(.leading, 5)
Spacer()
Button(action: {
}) {
Image(systemName: "mic.fill")
.foregroundColor(.black)
.padding(.trailing, 5)
}
}
}
.frame(height: 35)
.background(.quinary)
.cornerRadius(5)
.padding()
ForEach($list) { message in
MessageCell(message: message)
}
}
}
.navigationBarTitle("メッセージ")
.navigationBarItems(leading: Button("編集") {
})
.navigationBarItems(trailing: Button(action: {
sheet = true
}) {
Image(systemName: "square.and.pencil")
})
}
.sheet(isPresented: $sheet) {
NewMessageView()
}
}
}