Using List with SwiftUI
In this article, I will show you how to use List and NavigationBar with SwiftUI. This structure corresponds to the UITableView and UINavigationBar structure in UIKit.
You can quickly list our table and easily add NavigationBar to our page without dealing with structures such as Delegate and DataSource, which we are dealing with UIKit.
First of all, let’s create the model structure that we will list.
struct CityModel: Identifiable {
var id:Int
var name:String
}
When we add Identifiable to our model structure, we can sort according to the variable we want.
Then we create a view with our design for the column in our list and write our codes there.
struct CustomRow: View {
var city: CityModel
var body: some View {
HStack {
Image(uiImage: UIImage(named: "img.jpg")!)
.frame(width: 32, height: 32, alignment: .center)
.clipShape(Circle())
Text(city.name)
.bold()
.padding(.leading, 10)
}
}
}
And finally, we create our list on our home page and list our column view structure here.
struct CustomView:View {
let citys = [CityModel(id: 0, name: "San Francisco"), CityModel(id: 1, name: "New York"),CityModel(id: 2, name: "Miami"),CityModel(id: 3, name: "Las Vegas")]
var body: some View {
NavigationView {
List(citys.identified(by: \.id)) { city in
CustomRow(city: city)
}
.navigationBarTitle(Text("Citys"), displayMode: .large)
}
}
}
Post Comment