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)
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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"),
]
I am searching for a long time, how we can use custom emoji in SwiftUI, for a chat app, there is some example on internet but they are not for custom emoji, is it possible 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)
}
}}
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)
}
}}
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)
}
}
}
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
}
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"))
}
})
}
}
}
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()
}
}
}
}
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)
}
}
}
}
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?
I have simple app, when I run my project it work, but then throw error after running like "Thread 1: Fatal error: No ObservableObject of type msgDatas found. A View.environmentObject(_:) for msgDatas may be missing as an ancestor of this view."
struct Home: View {
@EnvironmentObject var data : msgDatas
var body : some View{
ZStack{
Color("bg").edgesIgnoringSafeArea(.top)
NavigationLink(destination: Message(), isActive: $data.show) {
Text("")
}
VStack{
topView()
}
}
}
}
Hi every one, if you build a mobile project with SwiftUI, is it possible to use the app for sub version of IOS like iPhone 6s devices ?
I have searchBarTextDidEndEditing func , but when I want to call searchBar in other func like that
`search.searchBar.showLoading()`
it throw error like that "Value of type 'UISearchBar' has no member 'showLoading'"
searchBarTextDidEndEditing func:
`
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
self.search.animationController(forDismissed: self)
self.search.automaticallyShowsSearchResultsController = false
}`
I want to use segue when I click the forget password icon , Iit may open "ForgotPasswordEmailCheckController" view, my code is running but it throw error like "Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<MyApp.LoginViewController 0x7fa962b13730> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key forgotPassword.'" I don't know why?
ForgotPasswordEmailCheckController:
class ForgotPasswordEmailCheckController: UIViewController, UITextFieldDelegate {
var storyboardId: String {
return (value(forKey: "ForgotPasswordEmailCheckController") as? String)!
}
LoginViewController:
@IBAction func forgotPassword(_ sender: Any) {
let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
guard let forgotPasswordEmailCheckCotroller = mainStoryboard.instantiateViewController(identifier: "ForgotPasswordEmailCheckController") as?
ForgotPasswordEmailCheckController else {
print("Not correct password")
return
}
navigationController?.pushViewController(forgotPasswordEmailCheckCotroller, animated: true)
}