Post

Replies

Boosts

Views

Activity

Why I am not able to use two screen for registration in SwiftUI?
I have register screen in SwiftUI, and I want to use two screen for register users, one view have mail and password, and other view have name surname and occupation, but I am still do not understand how I will connect both register view, any idea? RegistrationViewModel: enum RegistrationState { case successfullyRegistered case failed(error: Error) case na } protocol RegistrationViewModel { func create() var service: RegistrationService { get } var state: RegistrationState { get } var hasError: Bool { get } var newUser: RegistrationCredentials { get } init(service: RegistrationService) } final class RegistrationViewModelImpl: ObservableObject, RegistrationViewModel { let service: RegistrationService @Published var state: RegistrationState = .na @Published var newUser = RegistrationCredentials(email: "", password: "", firstName: "", lastName: "", occupation: "") @Published var hasError: Bool = false private var subscriptions = Set<AnyCancellable>() init(service: RegistrationService) { self.service = service setupErrorSubscription() } func create() { service .register(with: newUser) .sink { [weak self] res in switch res { case .failure(let error): self?.state = .failed(error: error) default: break } } receiveValue: { [weak self] in self?.state = .successfullyRegistered } .store(in: &subscriptions)}} private extension RegistrationViewModelImpl { func setupErrorSubscription() { $state .map { state -> Bool in switch state { case .successfullyRegistered, .na: return false case .failed: return true}} .assign(to: &$hasError)}} firstscreen: struct RegisterView: View { @StateObject private var viewModel = RegistrationViewModelImpl( service: RegistrationServiceImpl() ) var body: some View { NavigationView { VStack(spacing: 32) { VStack(spacing: 16) { InputTextFieldView(text: $viewModel.newUser.email, placeholder: "Email", keyboardType: .emailAddress, systemImage: "envelope") InputPasswordView(password: $viewModel.newUser.password, placeholder: "Password", systemImage: "lock") } ButtonView(title: "Next") { viewModel.create() } } .padding(.horizontal, 15) .alert(isPresented: $viewModel.hasError, content: { if case .failed(let error) = viewModel.state { return Alert( title: Text("Error"), message: Text(error.localizedDescription)) } else { return Alert( title: Text("Error"), message: Text("Something went wrong")) }})}}} secondscreen: import SwiftUI struct SecondRegisterView: View { @StateObject private var viewModel = RegistrationViewModelImpl( service: RegistrationServiceImpl() ) var body: some View { NavigationView { VStack(spacing: 32) { VStack(spacing: 16) { InputTextFieldView(text: $viewModel.newUser.firstName, placeholder: "First Name", keyboardType: .namePhonePad, systemImage: nil) InputTextFieldView(text: $viewModel.newUser.lastName, placeholder: "Last Name", keyboardType: .namePhonePad, systemImage: nil) InputTextFieldView(text: $viewModel.newUser.occupation, placeholder: "Occupation", keyboardType: .namePhonePad, systemImage: nil) } ButtonView(title: "Sign up") { viewModel.create() } } .padding(.horizontal, 15) .navigationTitle("Register") .applyClose() .alert(isPresented: $viewModel.hasError, content: { if case .failed(let error) = viewModel.state { return Alert( title: Text("Error"), message: Text(error.localizedDescription)) } else { return Alert( title: Text("Error"), message: Text("Something went wrong")) } }) } } }
1
0
822
Mar ’22
Why I am not able to use mobile authentication for firebase in SwiftUI project?
I have a problem in my SwiftUI project, I try to use mobile authentication with firebase, when I put my number and click the button , it is throw an error as a If app delegate swizzling is disabled, remote notifications received by UIApplicationDelegate need to be forwarded to FIRAuth's canHandleNotification: method. I am still do not understand what I missed? @State var no = "" @State var show = false @State var msg = "" @State var alert = false @State var ID = "" var body : some View{ VStack{ TextField("No",text:self.$no) NavigationLink(destination: CodeView(show: $show, ID: $ID), isActive: $show) { Button { PhoneAuthProvider.provider().verifyPhoneNumber(self.no, uiDelegate: nil) { (ID, err) in if err != nil{ self.msg = (err?.localizedDescription)! self.alert.toggle() return } self.ID = ID! self.show.toggle() } } label: { Text("OK") .padding() } } } .alert(isPresented: $alert) { Alert(title: Text("Error"), message: Text(self.msg), dismissButton: .default(Text("Ok"))) } } CodeView: @State var scode = "" @State var show = false @State var msg = "" @State var alert = false @State var ID = "" VStack { TextField("SMS Code", text: self.$scode) NavigationLink(destination: HomeView(), isActive: $show) { Button { let credential = PhoneAuthProvider.provider().credential(withVerificationID: self.ID, verificationCode: self.scode) Auth.auth().signIn(with: credential) { (res, err) in if err != nil{ self.msg = (err?.localizedDescription)! self.alert.toggle() return } UserDefaults.standard.set(true, forKey: "status") NotificationCenter.default.post(name: NSNotification.Name("statusChange"), object: nil) } } label: { Text("Next") .padding() } } .alert(isPresented: $alert) { Alert(title: Text("Error"), message: Text(self.msg), dismissButton: .default(Text("Ok"))) } MyApp: import SwiftUI import Firebase @main struct App: App { init() { FirebaseApp.configure() } var body: some Scene { WindowGroup { ZStack{ ContentView() } } } }
1
0
1.7k
Mar ’22
How can I use custom image instead of the ImagePicker in SwiftUI?
I have simple chat app, and it is work for image picker, but I have custom image view and it fetch the images from internet, I want to use them instead of the image picker in my phone, but I did not find any solution, is there any idea about it? struct Home: View { @State var message = "" @State var imagePicker = false @State var imgData: Data = Data(count: 0) @StateObject var allMessages = Messages() var body: some View { ZStack { VStack { VStack { // Displaying Message ScrollView(.vertical, showsIndicators: true) { ScrollViewReader { reader in VStack(spacing: 20) { ForEach(allMessages.messages) { msg in ChatBubble(msg: msg) } .onChange(of: allMessages.messages) { value in if value.last!.myMsg { reader.scrollTo(value.last?.id) }}}}}}} .clipShape(RoundedRectangle(cornerRadius: 35))} VStack { HStack(spacing: 15) { HStack(spacing: 15) { TextField("Message", text: $message) Button(action: { // toggling image picker imagePicker.toggle() }) { Image(systemName: "paperclip.circle.fill") .font(.system(size: 22)) .foregroundColor(.gray)} .background(Color.black.opacity(0.06)) .clipShape(Capsule()) if message != "" { Button(action: { withAnimation(.easeIn) { allMessages.messages.append(Message(id: Date(), message: message, myMsg: true, profilePic: "p1", photo: nil)) } message = "" }) { Image(systemName: "paperplane.fill") .font(.system(size: 22)) .foregroundColor(Color("Color")) // rotating the image .rotationEffect(.init(degrees: 45)) .clipShape(Circle())}}} .padding(.bottom) .padding(.horizontal) .background(Color.white) .animation(.easeOut) } .fullScreenCover(isPresented: $imagePicker, onDismiss: { if imgData.count != 0 { allMessages.writeMessage(id: Date(), msg: "", photo: imgData, myMsg: true, profilePic: "p1") } }) { ImagePicker(imagePicker: $imagePicker, imgData: $imgData) }}}} struct ChatBubble: View { var msg: Message var body: some View { HStack(alignment: .top, spacing: 10) { if msg.myMsg { if msg.photo == nil { Text(msg.message) .padding(.all) .background(Color.black.opacity(0.06)) .clipShape(BubbleArrow(myMsg: msg.myMsg)) } else { Image(uiImage: UIImage(data: msg.photo!)!) .resizable() .frame(width: UIScreen.main.bounds.width - 150, height: 150) .clipShape(BubbleArrow(myMsg: msg.myMsg)) } Image(msg.profilePic) .resizable() .frame(width: 30, height: 30) .clipShape(Circle()) } else { Image(msg.profilePic) .resizable() .frame(width: 30, height: 30) .clipShape(Circle()) if msg.photo == nil { Text(msg.message) .foregroundColor(.white) .padding(.all) .background(Color("Color")) .clipShape(BubbleArrow(myMsg: msg.myMsg)) } else { Image(uiImage: UIImage(data: msg.photo!)!) .resizable() .frame(width: UIScreen.main.bounds.width - 150, height: 150) .clipShape(BubbleArrow(myMsg: msg.myMsg))}}} .id(msg.id)}} struct RoundedShape: Shape { func path(in rect: CGRect) -> Path { let path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 35, height: 35)) return Path(path.cgPath) } } struct Message: Identifiable, Equatable { var id: Date var message: String var myMsg: Bool var profilePic: String var photo: Data? } class Messages: ObservableObject { @Published var messages: [Message] = [] init() { let strings = ["Hii", "Hello!!", "What's up?", "What Are you doing?", "Nothing, just enjoying quarantine holidays.. you??", "Same :))", "Ohhh", "What about your country?", "Very very bad..", "Ok, be safe.", "Ok", "Bye"] for i in 0..<strings.count { // simple logic for two side message View messages.append(Message(id: Date(), message: strings[i], myMsg: i % 2 == 0, profilePic: i % 2 == 0 ? "p1" : "p2")) } } func writeMessage(id: Date, msg: String, photo: Data?, myMsg: Bool, profilePic: String) { messages.append(Message(id: id, message: msg, myMsg: myMsg, profilePic: profilePic, photo: photo)) } } CustomImageView: struct CustomImageView: View { private let threeColumnGrid = [ GridItem(.flexible(minimum: 40)), GridItem(.flexible(minimum: 40)), GridItem(.flexible(minimum: 40)), ] var body: some Scene { LazyVGrid(columns: threeColumnGrid, alignment: .center) { ForEach(model.imageNames, id: \.self) { item in GeometryReader { gr in Image(item) .resizable() .scaledToFill() .frame(height: gr.size.width) } .clipped() .aspectRatio(1, contentMode: .fit) } } } }
1
0
1.1k
Mar ’22
why HStack items not alignnment in SwiftUI?
I have simple project in swiftUI, everythings is work, but HStack for  Rectangle() as I mention below, do not alignment the Rectangle and text at the same line, and idea will be appreciated. struct App: View {   var body: some View {         GeometryReader{g in              ZStack {         ForEach(0..data.count) { i in           DrawShape(center: CGPoint(x:g.frame(in: .global).width/2, y: g.frame(in: .global).height/2), index: i)         }              }     }     .frame(height: 200)          .clipShape(Circle())     .shadow(radius: 10)         VStack{       ForEach(data) { i in         HStack {                     Text(i.name)             .frame(width:100)             .padding()                      GeometryReader { g in             HStack{               Spacer(minLength: 0)               Rectangle()                 .fill(i.color)                 .frame(width: self.getWidth(width: g.frame(in: .global).width, value: i.percent) ,height: 10)                                              Text(String(format: "\(i.percent)", "%.0f"))                 .fontWeight(.bold)                 .padding(.leading,10)                 .frame(width:80)                Spacer()                                            }.frame(width: 240, height: 30)                                      }                     }                 }       .padding()       Spacer()     }                       }   func getWidth(width: CGFloat, value: CGFloat) - CGFloat {     let temp = value / 100     return temp * width   } }
3
0
3.4k
May ’21
How can I handle NavigationLink for HStack row
I want to use NavigationLink for open the chat detail view when I click the rows items. Here example of code I mentioned. Any idea will be appreciated. RecentRowView: import SwiftUI struct RecentRowView: View { var recent: Profile var animation: Namespace.ID // Environment Object... @EnvironmentObject var profileData: ProfileDetailModel var body: some View { HStack(spacing: 15){ // Making it as clickable Button.... Button(action: { withAnimation{ profileData.selectedProfile = recent profileData.showProfile.toggle() } }, label: { ZStack{ // Without matched geometry effect simply showing image... Image(recent.profile) .resizable() .aspectRatio(contentMode: .fill) .frame(width: 60, height: 60) .clipShape(Circle()) if !profileData.showProfile{ Image(recent.profile) .resizable() .aspectRatio(contentMode: .fill) // Matched Geometry Effect... // Giving unique ID that is from UUID from profile Model.... .matchedGeometryEffect(id: recent.id, in: animation) .frame(width: 60, height: 60) .clipShape(Circle()) } } }) // it decreased the highlight color.... .buttonStyle(PlainButtonStyle()) VStack{   NavigationLink(destination: ChatDetailView(), isActive: $profileData.show) { HStack{ VStack(alignment: .leading, spacing: 8, content: { Text(recent.userName) .fontWeight(.bold) Text(recent.lastMsg) .font(.caption) .foregroundColor(.gray) }) Spacer(minLength: 10) Text(recent.time) .font(.caption2) .foregroundColor(.gray) } Divider() } } } .padding(.horizontal) } } struct RecentRowView_Previews: PreviewProvider { static var previews: some View { ContentView() } } ContentView: struct ContentView: View { // ANimation Namespace... @Namespace var animation // StateObject... @StateObject var profileData = ProfileDetailModel() var body: some View { Home(animation: animation) // setting Environment Object... .environmentObject(profileData) } } struct ContentView_Previews: PreviewProvider { static var previews: some View {     NavigationView{ ContentView() } } } ChatDetailView: import SwiftUI struct ChatDetailView: View {   var body: some View {     Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)   } } struct ChatDetailView_Previews: PreviewProvider {   static var previews: some View {     ChatDetailView()   } }
6
0
2.2k
Jun ’21
Cannot convert value of type 'ForgotPasswordEmailCheckController.Type' to expected argument type 'UIViewController'?
I want to use segue programmaticly , but it throw error for ForgotPasswordEmailCheckController as "Cannot convert value of type 'ForgotPasswordEmailCheckController.Type' to expected argument type 'UIViewController'" Any idea? ForgotPasswordEmailCheckController:  class ForgotPasswordEmailCheckController: UIViewController, UITextFieldDelegate {   var storyboardId: String {     return (value(forKey: "ForgotPasswordEmailCheck") as? String)!   } LoginViewController:     @IBAction func forgotPassword(_ sender: Any) {           let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)           guard let forgotPasswordEmailCheck = mainStoryboard.instantiateViewController(identifier: "ForgotPasswordEmailCheck") as?     ForgotPasswordEmailCheckController else {       print("Not correct password")       return     }           navigationController?.pushViewController(ForgotPasswordEmailCheckController, animated: true)   }
1
0
1.3k
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
380
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
423
Oct ’21
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
503
Feb ’22
Why it is throw an error as "'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead" in SwiftUI?
I have project in SwiftUI 2.0 but when I update to SwiftUI 3.0 it is throw an error for windows as a windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead any idea?     .padding(.top, UIApplication.shared.windows.first?.safeAreaInsets.top)
0
0
682
Feb ’22
Why I am not able to use two screen for registration in SwiftUI?
I have register screen in SwiftUI, and I want to use two screen for register users, one view have mail and password, and other view have name surname and occupation, but I am still do not understand how I will connect both register view, any idea? RegistrationViewModel: enum RegistrationState { case successfullyRegistered case failed(error: Error) case na } protocol RegistrationViewModel { func create() var service: RegistrationService { get } var state: RegistrationState { get } var hasError: Bool { get } var newUser: RegistrationCredentials { get } init(service: RegistrationService) } final class RegistrationViewModelImpl: ObservableObject, RegistrationViewModel { let service: RegistrationService @Published var state: RegistrationState = .na @Published var newUser = RegistrationCredentials(email: "", password: "", firstName: "", lastName: "", occupation: "") @Published var hasError: Bool = false private var subscriptions = Set<AnyCancellable>() init(service: RegistrationService) { self.service = service setupErrorSubscription() } func create() { service .register(with: newUser) .sink { [weak self] res in switch res { case .failure(let error): self?.state = .failed(error: error) default: break } } receiveValue: { [weak self] in self?.state = .successfullyRegistered } .store(in: &subscriptions)}} private extension RegistrationViewModelImpl { func setupErrorSubscription() { $state .map { state -> Bool in switch state { case .successfullyRegistered, .na: return false case .failed: return true}} .assign(to: &$hasError)}} firstscreen: struct RegisterView: View { @StateObject private var viewModel = RegistrationViewModelImpl( service: RegistrationServiceImpl() ) var body: some View { NavigationView { VStack(spacing: 32) { VStack(spacing: 16) { InputTextFieldView(text: $viewModel.newUser.email, placeholder: "Email", keyboardType: .emailAddress, systemImage: "envelope") InputPasswordView(password: $viewModel.newUser.password, placeholder: "Password", systemImage: "lock") } ButtonView(title: "Next") { viewModel.create() } } .padding(.horizontal, 15) .alert(isPresented: $viewModel.hasError, content: { if case .failed(let error) = viewModel.state { return Alert( title: Text("Error"), message: Text(error.localizedDescription)) } else { return Alert( title: Text("Error"), message: Text("Something went wrong")) }})}}} secondscreen: import SwiftUI struct SecondRegisterView: View { @StateObject private var viewModel = RegistrationViewModelImpl( service: RegistrationServiceImpl() ) var body: some View { NavigationView { VStack(spacing: 32) { VStack(spacing: 16) { InputTextFieldView(text: $viewModel.newUser.firstName, placeholder: "First Name", keyboardType: .namePhonePad, systemImage: nil) InputTextFieldView(text: $viewModel.newUser.lastName, placeholder: "Last Name", keyboardType: .namePhonePad, systemImage: nil) InputTextFieldView(text: $viewModel.newUser.occupation, placeholder: "Occupation", keyboardType: .namePhonePad, systemImage: nil) } ButtonView(title: "Sign up") { viewModel.create() } } .padding(.horizontal, 15) .navigationTitle("Register") .applyClose() .alert(isPresented: $viewModel.hasError, content: { if case .failed(let error) = viewModel.state { return Alert( title: Text("Error"), message: Text(error.localizedDescription)) } else { return Alert( title: Text("Error"), message: Text("Something went wrong")) } }) } } }
Replies
1
Boosts
0
Views
822
Activity
Mar ’22
Why I am not able to use mobile authentication for firebase in SwiftUI project?
I have a problem in my SwiftUI project, I try to use mobile authentication with firebase, when I put my number and click the button , it is throw an error as a If app delegate swizzling is disabled, remote notifications received by UIApplicationDelegate need to be forwarded to FIRAuth's canHandleNotification: method. I am still do not understand what I missed? @State var no = "" @State var show = false @State var msg = "" @State var alert = false @State var ID = "" var body : some View{ VStack{ TextField("No",text:self.$no) NavigationLink(destination: CodeView(show: $show, ID: $ID), isActive: $show) { Button { PhoneAuthProvider.provider().verifyPhoneNumber(self.no, uiDelegate: nil) { (ID, err) in if err != nil{ self.msg = (err?.localizedDescription)! self.alert.toggle() return } self.ID = ID! self.show.toggle() } } label: { Text("OK") .padding() } } } .alert(isPresented: $alert) { Alert(title: Text("Error"), message: Text(self.msg), dismissButton: .default(Text("Ok"))) } } CodeView: @State var scode = "" @State var show = false @State var msg = "" @State var alert = false @State var ID = "" VStack { TextField("SMS Code", text: self.$scode) NavigationLink(destination: HomeView(), isActive: $show) { Button { let credential = PhoneAuthProvider.provider().credential(withVerificationID: self.ID, verificationCode: self.scode) Auth.auth().signIn(with: credential) { (res, err) in if err != nil{ self.msg = (err?.localizedDescription)! self.alert.toggle() return } UserDefaults.standard.set(true, forKey: "status") NotificationCenter.default.post(name: NSNotification.Name("statusChange"), object: nil) } } label: { Text("Next") .padding() } } .alert(isPresented: $alert) { Alert(title: Text("Error"), message: Text(self.msg), dismissButton: .default(Text("Ok"))) } MyApp: import SwiftUI import Firebase @main struct App: App { init() { FirebaseApp.configure() } var body: some Scene { WindowGroup { ZStack{ ContentView() } } } }
Replies
1
Boosts
0
Views
1.7k
Activity
Mar ’22
How can I use custom image instead of the ImagePicker in SwiftUI?
I have simple chat app, and it is work for image picker, but I have custom image view and it fetch the images from internet, I want to use them instead of the image picker in my phone, but I did not find any solution, is there any idea about it? struct Home: View { @State var message = "" @State var imagePicker = false @State var imgData: Data = Data(count: 0) @StateObject var allMessages = Messages() var body: some View { ZStack { VStack { VStack { // Displaying Message ScrollView(.vertical, showsIndicators: true) { ScrollViewReader { reader in VStack(spacing: 20) { ForEach(allMessages.messages) { msg in ChatBubble(msg: msg) } .onChange(of: allMessages.messages) { value in if value.last!.myMsg { reader.scrollTo(value.last?.id) }}}}}}} .clipShape(RoundedRectangle(cornerRadius: 35))} VStack { HStack(spacing: 15) { HStack(spacing: 15) { TextField("Message", text: $message) Button(action: { // toggling image picker imagePicker.toggle() }) { Image(systemName: "paperclip.circle.fill") .font(.system(size: 22)) .foregroundColor(.gray)} .background(Color.black.opacity(0.06)) .clipShape(Capsule()) if message != "" { Button(action: { withAnimation(.easeIn) { allMessages.messages.append(Message(id: Date(), message: message, myMsg: true, profilePic: "p1", photo: nil)) } message = "" }) { Image(systemName: "paperplane.fill") .font(.system(size: 22)) .foregroundColor(Color("Color")) // rotating the image .rotationEffect(.init(degrees: 45)) .clipShape(Circle())}}} .padding(.bottom) .padding(.horizontal) .background(Color.white) .animation(.easeOut) } .fullScreenCover(isPresented: $imagePicker, onDismiss: { if imgData.count != 0 { allMessages.writeMessage(id: Date(), msg: "", photo: imgData, myMsg: true, profilePic: "p1") } }) { ImagePicker(imagePicker: $imagePicker, imgData: $imgData) }}}} struct ChatBubble: View { var msg: Message var body: some View { HStack(alignment: .top, spacing: 10) { if msg.myMsg { if msg.photo == nil { Text(msg.message) .padding(.all) .background(Color.black.opacity(0.06)) .clipShape(BubbleArrow(myMsg: msg.myMsg)) } else { Image(uiImage: UIImage(data: msg.photo!)!) .resizable() .frame(width: UIScreen.main.bounds.width - 150, height: 150) .clipShape(BubbleArrow(myMsg: msg.myMsg)) } Image(msg.profilePic) .resizable() .frame(width: 30, height: 30) .clipShape(Circle()) } else { Image(msg.profilePic) .resizable() .frame(width: 30, height: 30) .clipShape(Circle()) if msg.photo == nil { Text(msg.message) .foregroundColor(.white) .padding(.all) .background(Color("Color")) .clipShape(BubbleArrow(myMsg: msg.myMsg)) } else { Image(uiImage: UIImage(data: msg.photo!)!) .resizable() .frame(width: UIScreen.main.bounds.width - 150, height: 150) .clipShape(BubbleArrow(myMsg: msg.myMsg))}}} .id(msg.id)}} struct RoundedShape: Shape { func path(in rect: CGRect) -> Path { let path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 35, height: 35)) return Path(path.cgPath) } } struct Message: Identifiable, Equatable { var id: Date var message: String var myMsg: Bool var profilePic: String var photo: Data? } class Messages: ObservableObject { @Published var messages: [Message] = [] init() { let strings = ["Hii", "Hello!!", "What's up?", "What Are you doing?", "Nothing, just enjoying quarantine holidays.. you??", "Same :))", "Ohhh", "What about your country?", "Very very bad..", "Ok, be safe.", "Ok", "Bye"] for i in 0..<strings.count { // simple logic for two side message View messages.append(Message(id: Date(), message: strings[i], myMsg: i % 2 == 0, profilePic: i % 2 == 0 ? "p1" : "p2")) } } func writeMessage(id: Date, msg: String, photo: Data?, myMsg: Bool, profilePic: String) { messages.append(Message(id: id, message: msg, myMsg: myMsg, profilePic: profilePic, photo: photo)) } } CustomImageView: struct CustomImageView: View { private let threeColumnGrid = [ GridItem(.flexible(minimum: 40)), GridItem(.flexible(minimum: 40)), GridItem(.flexible(minimum: 40)), ] var body: some Scene { LazyVGrid(columns: threeColumnGrid, alignment: .center) { ForEach(model.imageNames, id: \.self) { item in GeometryReader { gr in Image(item) .resizable() .scaledToFill() .frame(height: gr.size.width) } .clipped() .aspectRatio(1, contentMode: .fit) } } } }
Replies
1
Boosts
0
Views
1.1k
Activity
Mar ’22
Can pass my data in Web View form for SwiftUI?
I have a register view and when I complete my register, I want to pass register data in form from WebView, is there any way to do it?
Replies
0
Boosts
0
Views
569
Activity
Mar ’22
Why apple reject webview for Swift App?
I have a simple app and it has simple properties, like user register to app, and it connect the webview, webview has payment also, but I am search on internet, and many people says like that apps will reject by apple, any idea?
Replies
1
Boosts
0
Views
2.2k
Activity
Mar ’22
why HStack items not alignnment in SwiftUI?
I have simple project in swiftUI, everythings is work, but HStack for  Rectangle() as I mention below, do not alignment the Rectangle and text at the same line, and idea will be appreciated. struct App: View {   var body: some View {         GeometryReader{g in              ZStack {         ForEach(0..data.count) { i in           DrawShape(center: CGPoint(x:g.frame(in: .global).width/2, y: g.frame(in: .global).height/2), index: i)         }              }     }     .frame(height: 200)          .clipShape(Circle())     .shadow(radius: 10)         VStack{       ForEach(data) { i in         HStack {                     Text(i.name)             .frame(width:100)             .padding()                      GeometryReader { g in             HStack{               Spacer(minLength: 0)               Rectangle()                 .fill(i.color)                 .frame(width: self.getWidth(width: g.frame(in: .global).width, value: i.percent) ,height: 10)                                              Text(String(format: "\(i.percent)", "%.0f"))                 .fontWeight(.bold)                 .padding(.leading,10)                 .frame(width:80)                Spacer()                                            }.frame(width: 240, height: 30)                                      }                     }                 }       .padding()       Spacer()     }                       }   func getWidth(width: CGFloat, value: CGFloat) - CGFloat {     let temp = value / 100     return temp * width   } }
Replies
3
Boosts
0
Views
3.4k
Activity
May ’21
How can I handle NavigationLink for HStack row
I want to use NavigationLink for open the chat detail view when I click the rows items. Here example of code I mentioned. Any idea will be appreciated. RecentRowView: import SwiftUI struct RecentRowView: View { var recent: Profile var animation: Namespace.ID // Environment Object... @EnvironmentObject var profileData: ProfileDetailModel var body: some View { HStack(spacing: 15){ // Making it as clickable Button.... Button(action: { withAnimation{ profileData.selectedProfile = recent profileData.showProfile.toggle() } }, label: { ZStack{ // Without matched geometry effect simply showing image... Image(recent.profile) .resizable() .aspectRatio(contentMode: .fill) .frame(width: 60, height: 60) .clipShape(Circle()) if !profileData.showProfile{ Image(recent.profile) .resizable() .aspectRatio(contentMode: .fill) // Matched Geometry Effect... // Giving unique ID that is from UUID from profile Model.... .matchedGeometryEffect(id: recent.id, in: animation) .frame(width: 60, height: 60) .clipShape(Circle()) } } }) // it decreased the highlight color.... .buttonStyle(PlainButtonStyle()) VStack{   NavigationLink(destination: ChatDetailView(), isActive: $profileData.show) { HStack{ VStack(alignment: .leading, spacing: 8, content: { Text(recent.userName) .fontWeight(.bold) Text(recent.lastMsg) .font(.caption) .foregroundColor(.gray) }) Spacer(minLength: 10) Text(recent.time) .font(.caption2) .foregroundColor(.gray) } Divider() } } } .padding(.horizontal) } } struct RecentRowView_Previews: PreviewProvider { static var previews: some View { ContentView() } } ContentView: struct ContentView: View { // ANimation Namespace... @Namespace var animation // StateObject... @StateObject var profileData = ProfileDetailModel() var body: some View { Home(animation: animation) // setting Environment Object... .environmentObject(profileData) } } struct ContentView_Previews: PreviewProvider { static var previews: some View {     NavigationView{ ContentView() } } } ChatDetailView: import SwiftUI struct ChatDetailView: View {   var body: some View {     Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)   } } struct ChatDetailView_Previews: PreviewProvider {   static var previews: some View {     ChatDetailView()   } }
Replies
6
Boosts
0
Views
2.2k
Activity
Jun ’21
Why it throw error after pod install as "Error installing MaterialControls" ?
When I pod install in terminal it say "[!] Error installing MaterialControls", Cloning into '/var/folders/w_/46rzmwwn0k73x1dtmmqk4m_r0000gn/T/d20210618-4079-1b04w72'... remote: Repository not found. fatal: repository 'https://github.com/fpt-software/Material-Controls-For-iOS.git/' not found. Any idea?
Replies
0
Boosts
0
Views
568
Activity
Jun ’21
Cannot convert value of type 'ForgotPasswordEmailCheckController.Type' to expected argument type 'UIViewController'?
I want to use segue programmaticly , but it throw error for ForgotPasswordEmailCheckController as "Cannot convert value of type 'ForgotPasswordEmailCheckController.Type' to expected argument type 'UIViewController'" Any idea? ForgotPasswordEmailCheckController:  class ForgotPasswordEmailCheckController: UIViewController, UITextFieldDelegate {   var storyboardId: String {     return (value(forKey: "ForgotPasswordEmailCheck") as? String)!   } LoginViewController:     @IBAction func forgotPassword(_ sender: Any) {           let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)           guard let forgotPasswordEmailCheck = mainStoryboard.instantiateViewController(identifier: "ForgotPasswordEmailCheck") as?     ForgotPasswordEmailCheckController else {       print("Not correct password")       return     }           navigationController?.pushViewController(ForgotPasswordEmailCheckController, animated: true)   }
Replies
1
Boosts
0
Views
1.3k
Activity
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])   } }
Replies
1
Boosts
0
Views
380
Activity
Aug ’21
Is it possible to update SwiftUI 2.0 project to Swift 3.0?
I have project in SwiftUI 2.0 and I want to update it for Swift 3.0, is it possible to do that?
Replies
2
Boosts
0
Views
982
Activity
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")), ] }
Replies
1
Boosts
0
Views
1.2k
Activity
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()   } }
Replies
1
Boosts
0
Views
423
Activity
Oct ’21
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())                  }}}}
Replies
1
Boosts
0
Views
503
Activity
Feb ’22
Why it is throw an error as "'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead" in SwiftUI?
I have project in SwiftUI 2.0 but when I update to SwiftUI 3.0 it is throw an error for windows as a windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead any idea?     .padding(.top, UIApplication.shared.windows.first?.safeAreaInsets.top)
Replies
0
Boosts
0
Views
682
Activity
Feb ’22