Post

Replies

Boosts

Views

Activity

Change icons border when click the bottom tab bar in Swift
I have custom bottom navigation bar in IOS application, everythings work very well, and I want to change bottom navigation items tint color when I click the items, and I was use the self.imgView.image!.withRenderingMode(.alwaysTemplate) self.imgView.tintColor = .red in isSelected, and it is change whole icons border tint color. I do not know where I miss, any idea? RootStackTabViewController: class RootStackTabViewController: UIViewController { @IBOutlet weak var bottomStack: UIStackView! var currentIndex = 0 lazy var tabs: [StackItemView] = { var items = [StackItemView]() for _ in 0..<5 { items.append(StackItemView.newInstance) } return items }() lazy var tabModels: [BottomStackItem] = { return [ BottomStackItem(title: "Home", image: "home"), BottomStackItem(title: "Favorites", image: "heart"), BottomStackItem(title: "Search", image: "search"), BottomStackItem(title: "Profile", image: "user"), BottomStackItem(title: "Settings", image: "settings") ] }() override func viewDidLoad() { super.viewDidLoad() self.setupTabs() } func setupTabs() { for (index, model) in self.tabModels.enumerated() { let tabView = self.tabs[index] model.isSelected = index == 0 tabView.item = model tabView.delegate = self self.bottomStack.addArrangedSubview(tabView) } } } StackItemView: protocol StackItemViewDelegate: AnyObject { func handleTap(_ view: StackItemView) } class StackItemView: UIView { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var highlightView: UIView! private let higlightBGColor = UIColor(hexString: "1160FB") static var newInstance: StackItemView { return Bundle.main.loadNibNamed( StackItemView.className(), owner: nil, options: nil )?.first as! StackItemView } weak var delegate: StackItemViewDelegate? override func awakeFromNib() { super.awakeFromNib() self.addTapGesture() } var isSelected: Bool = false { willSet { self.updateUI(isSelected: newValue) self.titleLabel.textColor = UIColor.white self.imgView.image!.withRenderingMode(.alwaysTemplate) self.imgView.tintColor = .red } } var item: Any? { didSet { self.configure(self.item) } } private func configure(_ item: Any?) { guard let model = item as? BottomStackItem else { return } self.titleLabel.text = model.title self.imgView.image = UIImage(named: model.image) self.isSelected = model.isSelected } private func updateUI(isSelected: Bool) { guard let model = item as? BottomStackItem else { return } model.isSelected = isSelected let options: UIView.AnimationOptions = isSelected ? [.curveEaseIn] : [.curveEaseOut] UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5, options: options, animations: { self.titleLabel.text = isSelected ? model.title : "" let color = isSelected ? self.higlightBGColor : .white self.highlightView.backgroundColor = color (self.superview as? UIStackView)?.layoutIfNeeded() }, completion: nil) } } extension StackItemView { func addTapGesture() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleGesture(_:))) self.addGestureRecognizer(tapGesture) } @objc func handleGesture(_ sender: UITapGestureRecognizer) { self.delegate?.handleTap(self) } }
1
0
1.1k
Jul ’21
Why image detail view just show one image from listview?
I have list image and when I click the image list items it show me image details, but it show same image even I click the different image? any idea? Datas:  struct Datas: Identifiable {   var id = UUID().uuidString   var name: String   var detail: String   var image: String } var datas = [   Datas(name: "People1.jpg"),   Datas(name: "People.2jpg"),   Datas(name: "People3.jpg"), ] RowView: struct RowView: View {   var docs: Datas   var body: some View {  NavigationLink(destination:  ListDetailsView(docs: datas[0])) {       Image(docs.image)         .resizable()         .frame(width: 64, height: 48)         } } ListDetailsView: struct ListDetailsView: View {    var docs: Datas       var body: some View {           ZStack{       Image(docs.image)     }         } } struct ListDetailsView_Previews: PreviewProvider {   static var previews: some View {     ListDetailsView(docs: datas[0])   } }
1
0
364
Aug ’21
why it says "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"?
I have IOS projets, it work but suddenly crash and throw error like "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" Why? import Foundation import AVFoundation struct Video : Identifiable {   var id = UUID()   var player : AVPlayer   var user: User } struct User: Identifiable {   var id = UUID()   let userName: String   let userImage: String } struct MockData {   let videos: [Video] = [     Video(player: AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "reel_1", ofType: "mp4")!)),        user: User(userName: "cristiano", userImage: "user_9")),     Video(player: AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "reel_2", ofType: "mp4")!)),        user: User(userName: "mann_daar", userImage: "user_3")), ] }
1
0
1.2k
Sep ’21
Cannot convert value of type 'AnyViewModel<BookListState, Never>.Type' to expected argument type 'AnyViewModel<BookListState, Never>'
I want to put BookListView() on the content view but it throw error like "Cannot convert value of type 'AnyViewModel<BookListState, Never>.Type' to expected argument type 'AnyViewModel<BookListState, Never>'" Any idea? BookListView: import SwiftUI struct BookListState {   var service: BookService   var books: [Book] } struct BookListView: View {   @ObservedObject var viewModel: AnyViewModel<BookListState, Never>   var body: some View {     NavigationView {       ScrollView {       VStack(alignment: .leading){       ForEach(viewModel.state.books) { book in         NavigationLink(destination: NavigationLazyView(BookDetailView(service: self.viewModel.state.service, bookId: book.id))) {           BookRow(book: book)         }       }             }       }     }   } } struct BookListView_Previews: PreviewProvider {   static var previews: some View {     let viewModel = AnyViewModel(BookListViewModel(service: MockBookService()))     return BookListView(viewModel: viewModel)   } } ContentView: import SwiftUI struct ContentView: View {   var body: some View {    BookListView(viewModel: viewModel)   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } }
1
0
411
Oct ’21
How can I resize bottom sheet height?
I am using bottom sheet for my app, and it is work correctly, but I want to use the half bottom sheet, is it possible?      Image( "color")               .resizable()               .frame(width:45, height: 45)               .sheet(isPresented: $showSheet, content: {                   ScreenView()                  })
1
0
1.3k
Jul ’22
Why NavigationLink not work for text button in SwiftUI?
I have text button, and I want to use navigation link in this project, but it is not work when I click the button? Any idea?   @State var isLink = false       var body: some View {     GeometryReader { geometry in         ZStack {    NavigationLink(destination: SecondView(), isActive: $isLink) {                 Button() {                   self.isLink = true                 } label: {                                       Text("Button")                     .padding()                     .frame(width: 250, height: 50, alignment: .center)                     .foregroundColor(Color.white)                     .background(Color("color"))                     .clipShape(Capsule())                  }}}}
1
0
491
Feb ’22
why it throw an error as "'animation' was deprecated in iOS 15.0: Use withAnimation or animation(_:value:) instead"in SwiftUI 3.0?
I have a project, after update it to swiftUI 3.0, it is throw an error for    .animation(.spring()) as animation' was deprecated in iOS 15.0: Use withAnimation or animation(_:value:) instead, any idea?  @Binding var display: Bool   private var background: some View {   Color.black    .fillParent()    .opacity(0.6)    .animation(.spring())  }
1
0
691
Feb ’22
Why I am not success to pass data from one view to another view in SwiftUI?
I have a problem when try to pass data from one view to another view, it is throw an error for   ImageDetails() as a "Missing argument for parameter 'data' in call" I do not know what I missed? struct ImageModel: Identifiable, Hashable {   var id = UUID().uuidString   var name: String   } var datas = [       ImageModel(name: "davis"), ] struct ImageRowView: View {   var data: ImageModel   var body: some View {            NavigationLink(destination: ImageDetailsView(data: ImageModel)){                       HStack{} }}} struct ImageDetailsView: View {      var body: some View {           ImageDetails()   } } struct ImageDetailsView_Previews: PreviewProvider {   static var previews: some View {           ImageDetailsView()         } } struct ImageDetails : View {      var data: ImageModel   var body: some View{   VStack{             Text(data.name)                      } }
1
0
435
Feb ’22
Why I am not success to pass data from one view to another view for many data in SwiftUI?
I ask this question before, it was answered but it is not work for many data, like when I click the any list items, all details pass name of "david", I want to pass data of user which I clicked, where I missed here? struct ImageModel: Identifiable, Hashable {   var id = UUID().uuidString   var name: String   } var datas = [       ImageModel(name: "davis"),  ImageModel(name: "carry"),   ImageModel(name: "maria"), ] struct ImageRowView: View {   var data: ImageModel   var body: some View {            NavigationLink(destination: ImageDetailsView(data: ImageModel)){                       HStack{} }}} struct ImageDetailsView: View {      var body: some View {          ImageDetails(data:  ImageModel(name: "davis"))   } } struct ImageDetailsView_Previews: PreviewProvider {   static var previews: some View {           ImageDetailsView()         } } struct ImageDetails : View {      var data: ImageModel   var body: some View{   VStack{             Text(data.name)                      } }
1
0
477
Feb ’22
why it is throw an error as a Value of type 'ContentView' has no member 'restaurants' in SwiftUI?
I have example of swiftUI project, and it is throw an error as a "Value of type 'ContentView' has no member 'restaurants'" for    self.restaurants.remove(atOffsets: indexSet) } line of code, I do not know what I missed, any idea? import SwiftUI struct ContentView: View {          @State private var selectedRestaurant: Restaurant?       var body: some View {     List {       ForEach(restaurants) { restaurant in         BasicImageRow(restaurant: restaurant)           .contextMenu {                           Button(action: {               // mark the selected restaurant as check-in               self.checkIn(item: restaurant)             }) {               HStack {                 Text("Check-in")                 Image(systemName: "checkmark.seal.fill")               }             }                           Button(action: {               // delete the selected restaurant               self.delete(item: restaurant)             }) {               HStack {                 Text("Delete")                 Image(systemName: "trash")               }             }                           Button(action: {               // mark the selected restaurant as favorite               self.setFavorite(item: restaurant)             }) {               HStack {                 Text("Favorite")                 Image(systemName: "star")               }             }           }           .onTapGesture {             self.selectedRestaurant = restaurant           }           .actionSheet(item: self.$selectedRestaurant) { restaurant in                           ActionSheet(title: Text("What do you want to do"), message: nil, buttons: [                               .default(Text("Mark as Favorite"), action: {                 self.setFavorite(item: restaurant)               }),                               .destructive(Text("Delete"), action: {                 self.delete(item: restaurant)               }),                               .cancel()             ])           }       }       .onDelete { (indexSet) in         self.restaurants.remove(atOffsets: indexSet)       }     }   }       private func delete(item restaurant: Restaurant) {     if let index = self.restaurants.firstIndex(where: { $0.id == restaurant.id }) {       self.restaurants.remove(at: index)     }   }       private func setFavorite(item restaurant: Restaurant) {     if let index = self.restaurants.firstIndex(where: { $0.id == restaurant.id }) {       self.restaurants[index].isFavorite.toggle()     }   }       private func checkIn(item restaurant: Restaurant) {     if let index = self.restaurants.firstIndex(where: { $0.id == restaurant.id }) {       self.restaurants[index].isCheckIn.toggle()     }   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } } struct BasicImageRow: View {   var restaurant: Restaurant       var body: some View {     HStack {       Image(restaurant.image)         .resizable()         .frame(width: 40, height: 40)         .cornerRadius(5)       Text(restaurant.name)               if restaurant.isCheckIn {         Image(systemName: "checkmark.seal.fill")           .foregroundColor(.red)       }               if restaurant.isFavorite {         Spacer()                   Image(systemName: "star.fill")           .foregroundColor(.yellow)       }     }   } } model: struct Restaurant: Identifiable {   var id = UUID()   var name: String   var image: String   var isFavorite: Bool = false   var isCheckIn: Bool = false } var restaurants = [ Restaurant(name: "Cafe Deadend", image: "cafedeadend"),        Restaurant(name: "Homei", image: "homei"),        Restaurant(name: "Teakha", image: "teakha"),        Restaurant(name: "Cafe Loisl", image: "cafeloisl"), ]
1
0
1.8k
Feb ’22
How we can use alert menu before delete list items in SwiftUI?
I have list items in SwiftUI, and when I delete list items, but when I click the delete button, it delete item randomly, I want to delete seleted item, where is the mistake? struct MyView: View { @State private var selectedUsers: MyModel?   @State var datas: [MyModel]    @State private var confirmDelete = false var body: some View { ScrollView(.vertical, showsIndicators: false, content: { VStack(content: { ForEach(datas){ data in MyRowView(data: data) .contextMenu { Button(action: { self.delete(item: data) }) { Text("delete") } } .onTapGesture { selectedUsers = data }   .confirmationDialog( "Are you sure ?",                   isPresented: $confirmDelete,                   titleVisibility: .visible                 ){                                       Button(role: .destructive) {                     self.delete(item: data)                   } label: {                     Text("ok")                                         }                   Button(role: .cancel) {                                         } label: {                     Text("cancel")                                         }                 }             } .onDelete { (indexSet) in self.datas.remove(atOffsets: indexSet) }}) })} private func delete(item data: MyModel) { if let index = datas.firstIndex(where: { $0.id == data.id }) { datas.remove(at: index) } }}
1
1
1k
Feb ’22
Why SwiftUI `confirmationDialog` delete the wrong item?
I am trying to use confirmationDialog to delete an item in a List. But what happens is that the wrong item gets deleted. Why? Here is my code: struct MyView: View { @State private var selectedUsers: MyModel?   @State var datas: [MyModel]    @State private var confirmDelete = false var body: some View { ScrollView(.vertical, showsIndicators: false, content: { VStack(content: { ForEach(datas){ data in MyRowView(data: data) .contextMenu { Button(action: { self.delete(item: data) }) { Text("delete") } } .onTapGesture { selectedUsers = data }   .alert(isPresented: $confirmDelete) {               Alert(title: Text("title"),                 message: Text("message"),                 primaryButton: .destructive(Text("Delete")) {                                 self.delete(item: data)                                   },                 secondaryButton: .cancel())             }                               } .onDelete { (indexSet) in self.datas.remove(atOffsets: indexSet) }}) })} private func delete(item data: MyModel) { if let index = datas.firstIndex(where: { $0.id == data.id }) { datas.remove(at: index) } }}
1
1
1k
Oct ’22
Why it says "Function is unused" in SwiftUI?
I have SwiftUI project, and I want to use register for my project, it throw an error as a "Function is unused" for signUp in this line of code: Button {                   self.viewModel.signUp                    } label: {                   Text("Register")                     .padding()                 } I do not know why? struct Register: View {       @ObservedObject private var viewModel: RegisterViewModel   @State var pushActive = false         init(state: AppState) {           self.viewModel = RegisterViewModel(authAPI: AuthService(), state: state)           }     var body: some View {    Button {                              self.viewModel.signUp                                     } label: {                   Text("Register")                     .padding()                                     } } viewmodel: class RegisterViewModel: ObservableObject {   @Published var email: String = ""   @Published var password: String = ""   @Published var state: AppState       private var cancellableBag = Set<AnyCancellable>()   private let authAPI: AuthAPI       init(authAPI: AuthAPI, state: AppState) {     self.authAPI = authAPI     self.state = state   }       func signUp() {     authAPI.signUp(email: email, password: password)       .receive(on: RunLoop.main)       .map(resultMapper)       .store(in: &cancellableBag)   } } }
1
0
4.1k
Mar ’22
why it say "Extra arguments at positions #3 , #4 in call" in SwiftUI?
I have small problem in my project, it throw an error as a Extra arguments at positions #3, #4 for  Auth.auth().signIn() line, I do not know what I missed? func login(email: String, password: String, name: String, surname: String) -> Future<User?, Never> { return Future<User?, Never> { promise in Auth.auth().signIn(withEmail: email, password: password, name: name, surname: surname) {(authResult, _) in guard let id = authResult?.user.providerID, let email = authResult?.user.email else { promise(.success(nil)) return } let user = User(id: id, email: email, name:name, surname:surname) promise(.success(user)) } } } model: import Foundation struct User { let id: String let email: String let name: String let surname: String }
1
0
768
Mar ’22