I have list item menu project in SwiftUI, my project work, but I have list icons, they are not shown in list view, even I was try to use system image, there is not any change on screen, any idea?
struct MasterView: View {
let view1 = Menu(name:"Home", image:"image_home", destination:.home)
let view2 = Menu(name:"View 1", image:"image_view1", destination:.view1)
let view3 = Menu(name:"View 3", image:"image_view2", destination:.view2)
var body: some View {
let menus: [Menu] = [view1, view2, view3]
return List {
ForEach(menus) { menu in
self.destinationView(menu: menu)
}}}
func destinationView(menu: Menu) - some View {
switch menu.destination {
case .view1:
return NavigationLink(
destination: AnyView(View1(menu: menu))
)
{
Text("\(menu.name)")
}
case .view2:
return NavigationLink(
destination: AnyView(View2(menu: menu))
)
{
Text("\(menu.name)")
}
default:
return NavigationLink(
destination: AnyView(HomeView(menu: menu))
)
{
Text("\(menu.name)")
}}}}
Model.swift:
/// Main menu item for the list
struct Menu: Identifiable {
var id = UUID()
var name: String
var image: String
var destination: ViewType
}
enum ViewType {
case home
case view1
case view2
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Code below throw error as cannot convert value of type 'EventsTrigger' to expected argument type 'String?, where I miss?
EventsTrigger class:
public class EventsTrigger: NSObject {
static let instance: EventsTrigger = EventsTrigger()
}
and
self.service = NewService("node4", EventsTrigger.instance, err)
The default colour of a list row when tapped is grey.
I try many solution on stackoverflow and apple form, I did not solve problem, any idea?
RecentRowView:
struct RecentRowView: View {
var body: some View {
HStack(spacing: 15){
List{
NavigationLink(destination: SecondView()
){
VStack{
HStack{
VStack(alignment: .leading, spacing: 8, content: {
Text(recent.name)
.font(.custom("Helvetica Neue", size: 14))
})
Spacer(minLength: 10)
ZStack {
}
}
}
}
}
}
}
}
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)
}
}
I have number.name array like 1.go, 2.java, 3.swift etc..and I do not want to edit the number again, user will only change name. Is it possible?
if words.count == 24 {
for (index, textField) in textFields.enumerated() {
textField.delegate = self
textField.firstDesign()
textField.text = "\(index + 1). \(words[index])"
mneArr.append(words[index])
}
I have data in row like Text(data.user) and I want to use searchable for it, I can use search bar, bat I want to use filter for user.
Text(data.user)
.searchable(text: $searchText, placement: .navigationBarDrawer)
like here, tere is some example for filter, but how can I use it for my data. Any idea?
.onChange(of: searchText) { searchText in
if !searchText.isEmpty {
articles = sampleArticles.filter { $0.title.contains(searchText) }
} else {
articles = sampleArticles
}
}
I am have a problem in general in SwiftUI, when we click any items we are open new view, but bottom nav bar still not hide, why there is not any solution in SwiftUI still?
I want to use many buttons like background have custom colors with grid view in swiftUI, is it possible? I know how to use grid layout for images, but I have confused to use for custom colors.
I have small restaurans data in content view, but I want to use this data shortly inside of the homeview,
I am typing to use
@State var restaurants: [ Restaurant]
but in other view I have HomeView, it is throw an error like
Cannot convert value of type '[Restaurant].Type' to expected argument type '[Restaurant]'
for
HomeView( restaurants: [Restaurant])
line of code, I do not know what I missed? Any idea?
struct HomeView: View {
@State 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 am use firebase for my SwiftUI App, and I want to register with mail, but when I typing my mail it is throw an error like
Oops! Something went wrong. Please try again.
I do not know why? here is my code:
StatusViewModel:
class StatusViewModel: Identifiable, ObservableObject {
var title: String
var message: String
init(title: String = "", message: String = "") {
self.title = title
self.message = message
}
static var signUpSuccessStatus: StatusViewModel {
return StatusViewModel(title: "Successful", message: "Your account has been created successfully")
}
static var logInSuccessStatus: StatusViewModel {
return StatusViewModel(title: "Successful", message: "Your account has been logged in successfully")
}
static var errorStatus: StatusViewModel {
return StatusViewModel(title: "Error", message: "Oops! Something went wrong. Please try again.")
}
}
RegisterViewModel:
import Foundation
import Combine
class RegisterViewModel: ObservableObject {
@Published var email: String = ""
@Published var password: String = ""
@Published var statusViewModel: StatusViewModel?
@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)
.replaceError(with: StatusViewModel.errorStatus)
.assign(to: \.statusViewModel, on: self)
.store(in: &cancellableBag)
}
}
extension RegisterViewModel {
private func resultMapper(with user: User?) -> StatusViewModel {
if user != nil {
state.currentUser = user
return StatusViewModel.signUpSuccessStatus
} else {
return StatusViewModel.errorStatus
}
}
}
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 {
NavigationLink(destination: HomeView(state: viewModel.state),
isActive: self.$pushActive) {
Button {
self.viewModel.signUp()
} label: {
Text("Register")
.padding()
}
}
}
}
I have multiple register screen in swiftUI, I did not understand how I will connect first register screen to second register screen, normally first register screen connect to main screen, but I want to connect first register screen to second register screen, and connect second register screen to main screen, how can I do it, any idea?
StatusViewModel:
class StatusViewModel: Identifiable, ObservableObject {
var title: String
var message: String
init(title: String = "", message: String = "") {
self.title = title
self.message = message
}
static var signUpSuccessStatus: StatusViewModel {
return StatusViewModel(title: "Successful", message: "Your account has been created successfully")
}
static var logInSuccessStatus: StatusViewModel {
return StatusViewModel(title: "Successful", message: "Your account has been logged in successfully")
}
static var errorStatus: StatusViewModel {
return StatusViewModel(title: "Error", message: "Oops! Something went wrong. Please try again.")
}
}
RegisterViewModel:
import Foundation
import Combine
class RegisterViewModel: ObservableObject {
@Published var email: String = ""
@Published var password: String = ""
@Published var statusViewModel: StatusViewModel?
@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)
.replaceError(with: StatusViewModel.errorStatus)
.assign(to: \.statusViewModel, on: self)
.store(in: &cancellableBag)
}
}
extension RegisterViewModel {
private func resultMapper(with user: User?) -> StatusViewModel {
if user != nil {
state.currentUser = user
return StatusViewModel.signUpSuccessStatus
} else {
return StatusViewModel.errorStatus
}
}
}
first register screen:
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 {
VStack(){
TextField("Email Address",text:$viewModel.email)
.autocapitalization(.none)
.padding()
HStack(spacing: 15){
TextField("Password", text: $viewModel.password)
.autocapitalization(.none)
}
NavigationLink(destination: HomeView(state: viewModel.state),
isActive: self.$pushActive) {
Button {
self.viewModel.signUp()
} label: {
Text("Register")
.padding()
}
}
}
}
second register screen:
struct SecondRegister: View {
var body: some View {
GeometryReader { geometry in
ZStack{
VStack(alignment: .center, spacing: 3){
TextField("First Name",text:self.$first_name)
.autocapitalization(.none)
.padding()
TextField("Last Name", text: self.$last_name)
.autocapitalization(.none)
.padding()
}
Button {
} label: {
Text("Next")
.padding()
}
}
}.padding()
}.padding(.top,60)
}
}
I have register screen and I am not able to register info to firebase, I put user info on simulator, but it just hold on on screen, and no any change on firebase, any idea? where I missed?
import SwiftUI
import Firebase
struct Register: View {
@State var name = ""
@State var about = ""
@Binding var show : Bool
var body: some View {
VStack(alignment: .center, spacing: 3){
TextField("Name",text:self.$name)
.padding()
TextField(" about", text: self.$about)
.padding()
if self.loading{
HStack{
Spacer()
Indicator()
Spacer()
}
}
else{
Button {
if self.name != "" && self.about != "" {
self.loading.toggle()
CreateUser(name: self.name, about: self.about) { (status) in
if status{
self.show.toggle()
}
}
}
else{
self.alert.toggle()
}
} label: {
Text("Next")
.padding()
}
}
}
import Foundation
import Firebase
func CreateUser(name: String,about : String, completion : @escaping (Bool)-> Void){
let db = Firestore.firestore()
let storage = Storage.storage().reference()
let uid = Auth.auth().currentUser?.uid
db.collection("users").document(uid!).setData(["name":name,"about":about, "uid":uid!]) { (err) in
if err != nil{
print((err?.localizedDescription)!)
return
}
completion(true)
UserDefaults.standard.set(true, forKey: "status")
UserDefaults.standard.set(name, forKey: "UserName")
NotificationCenter.default.post(name: NSNotification.Name("statusChange"), object: nil)
}
}
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()
}
}
}
}