I have a problem generating an error text.
#State private var email = ""
#State private var password = "Vignesh123!"
private func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %#", emailRegEx)
return emailPred.evaluate(with: email)
}
private func isPasswordValid(_ password : String) -> Bool{
let passwordFormat = "^(?=.*[A-Z])(?=.*[a-z])(?=.*?[0-9])(?=.*[$#$#!%*?&])[A-Za-z\\d$#$#!%*?&]{8,}"
let passwordTest = NSPredicate(format: "SELF MATCHES %#", passwordFormat)
return passwordTest.evaluate(with: password)
}
private func validView() -> String? {
if !self.isValidEmail(email) {
return "Email is invalid"
}
if !self.isPasswordValid(password) {
return "Password is invalid"
}
// Do same like other validation as per needed
return nil
}
during the code I wrote, I used TextField for the password to appear.
VStack(spacing: 0) {
Spacer()
VStack(alignment: .leading) {
TextField("Email", text: $email)
.textFieldStyle(DefaultTextFieldStyle())
.padding(.leading)
.frame(height: 50)
.background(.gray.opacity(0.3))
.cornerRadius(10)
.autocapitalization(.none)
if password.isEmpty {
Text("Email is Not Valid")
.font(.footnote).foregroundColor(.red).hidden()
} else if (self.validView() != nil) {
Text("Email is Not Valid")
.font(.footnote).foregroundColor(.red)
.padding(3)
}
}
VStack(alignment: .leading) {
TextField("Password", text: $password)
.textFieldStyle(DefaultTextFieldStyle())
.padding(.leading)
.frame(height: 50)
.background(.gray.opacity(0.3))
.cornerRadius(10)
.autocapitalization(.none)
if password.isEmpty {
Text("Password is Not Valid")
.font(.footnote).foregroundColor(.red).hidden()
} else if (self.validView() != nil) {
Text("Password is Not Valid")
.font(.footnote).foregroundColor(.red)
.padding(3)
}
}
Button(action: {
// Show error message here
if let errorMessage = self.validView() {
print(errorMessage)
return
}
}, label: {
Text("Login")
.frame(height: 45).frame(maxWidth: .infinity)
.background(.blue)
.foregroundColor(.white)
.cornerRadius(10)
})
Spacer()
}.padding()
result should be an error text should appear when I enter an inappropriate email / password and click on the Login
the above codes are my attempts 👆
I may be making elementary mistakes, I hope you understand correctly.
I appreciate your attention, thank you all
why dont you use a #State var showErrorMessage:Bool
In your password and email valid functions toggle the showErrorMessage. So if password is wrong toggle to true and if password is not wrong toggle to false.
On button click call this showErrorMessage, if true then show the Text.
Related
Here's my code, I don't get why this results in this transparent overlay when I move focus to the Text or SecureField components
struct SettingsPane: View {
// MARK: View state
#State private var isSecured: Bool = true
#State private var showApiKeyPopover: Bool = false
// MARK: Preference Storage
#AppStorage("preference_showWorkboard") var showWorkboard = true
#AppStorage("preference_userName") var userName = ""
#AppStorage("preference_jiraApiKey") var jiraApiKey = ""
// MARK: View dimensions
var frameWidth:CGFloat = 200
var body: some View {
Form {
Section(header: Text("Credentials")) {
TextField("User", text: $userName)
.textContentType(.username)
.frame(width: frameWidth)
HStack(alignment: .center) {
Group {
if isSecured {
SecureField("Jira API Key", text: $jiraApiKey)
.textContentType(.password)
.frame(width: frameWidth)
.lineLimit(1)
} else {
TextField("Jira API Key", text: $jiraApiKey)
.textContentType(.password)
.frame(width: frameWidth)
.lineLimit(1)
}
}.popover(isPresented: $showApiKeyPopover) {
Text("To get an API key visit your Jira profile.\nClick 'Personal Access Tokens' and create one named 'Firehose' and add it to this field")
.padding()
}
Button(action: {
isSecured.toggle()
}) {
Image(systemName: self.isSecured ? "eye.slash" : "eye")
.accentColor(.gray)
}
.buttonStyle(.borderless)
Button(action: {
showApiKeyPopover.toggle()
}) {
Image(systemName: "questionmark.circle.fill")
.accentColor(.gray)
}
.buttonStyle(.borderless)
}
Divider()
Section(header: Text("Features")) {
Toggle("Show Workboard", isOn: $showWorkboard)
}
}
}
.padding()
.frame(minWidth: 400, maxWidth: 400)
}
}
It works fine with me (macOS 13.0, Xcode 14.1). I get this ...
Could it be some password utility interfering?
I was given a signUp validation task. in doing so I tried my best. but I would like you to offer a better way or suggestion.
exception: Due to the correct email format, doSignUp () [Home page] is logged, even if the password format is incorrect
thanks for the attention
this is a view of my attempts 👇
#State var fullname = "Vignesh"
#State var email = "pdponline999#gmail.com"
#State var password = ""
#State var cpassword = ""
#State var showError1 = false
#State var showError2 = false
#State var shouldHide = false
let emailFormat = NSPredicate(format: "SELF MATCHES %#", "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}")
let passwordFormat = NSPredicate(format: "SELF MATCHES %#", "^(?=.*[A-Z])(?=.*[a-z])(?=.*?[0-9])(?=.*[$#$#!%*?&])[A-Za-z\\d$#$#!%*?&]{8,}")
TextField and SecureField
VStack(alignment: .leading) {
TextField("email", text: $email)
.frame(height: 45)
.padding(.leading)
.background(.white.opacity(0.4))
.cornerRadius(10)
.textInputAutocapitalization(.never)
if showError1 == true {
Text("Email is Not Valid")
.font(.footnote)
.fontWeight(.semibold)
.foregroundColor(.red)
.opacity(shouldHide ? 0 : 1)
}
}
VStack(alignment: .leading) {
SecureField("password", text: $password)
.frame(height: 45)
.padding(.leading)
.background(.white.opacity(0.4))
.cornerRadius(10)
if showError2 == true {
Text("Password is Not Valid")
.font(.footnote)
.fontWeight(.semibold)
.foregroundColor(.red)
.opacity(shouldHide ? 0 : 1)
}
}
Sign Up button
Button(action: {
if !emailFormat.evaluate(with: email) {
print("Check your email. And try again !!")
self.showError1 = true
self.shouldHide = false
} else {
self.showError1 = false
self.shouldHide = true
doSignUp()
}
if !passwordFormat.evaluate(with: password) {
print("Check your password. And try again !!")
self.showError2 = true
self.shouldHide = false
} else {
self.showError2 = false
self.shouldHide = true
doSignUp()
}
}, label: {
Text("sign_up")
.frame(maxWidth: .infinity).frame(height: 50)
.foregroundColor(.white)
.background(RoundedRectangle(cornerRadius: 10)
.stroke(lineWidth: 1.5)
.foregroundColor(.white.opacity(0.4)))
})
I'm trying to splice some code I found into a current SwiftUI view I have.
Basically, I want to make my segmented picker have colors that correspond to priority colors in a to-do list view.
Here is the sample code for the colored segmented picker. (Taken from HWS)
import SwiftUI
enum Colors: String, CaseIterable{
case red, yellow, green, blue
func displayColor() -> String {
self.rawValue.capitalized
}
}
struct TestView: View {
#State private var selectedColor = Colors.red
var body: some View {
Picker(selection: $selectedColor, label: Text("Colors")) {
ForEach(Colors.allCases, id: \.self) { color in
Text(color.displayColor())
}
}
.padding()
.colorMultiply(color(selectedColor))
.pickerStyle(SegmentedPickerStyle())
}
func color(_ selected: Colors) -> Color {
switch selected {
case .red:
return .red
case .yellow:
return .yellow
case .green:
return .green
case .blue:
return .blue
}
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
Then, here is the (complete because I don't have the chops to make MRE's yet– I'm still learning) code for the to-do list view (Taken from YouTube– I can't remember the creator's name, but I'll post it below once I find it again.):
import SwiftUI
enum Priority: String, Identifiable, CaseIterable {
var id: UUID {
return UUID()
}
case one = "Priority 1"
case two = "Priority 2"
case three = "Priority 3"
case four = "Priority 4"
}
extension Priority { //"priority.title"
var title: String {
switch self {
case .alloc:
return "Priority 1"
case .aoc:
return "Priority 2"
case .charting:
return "Priority 3"
case .clinical:
return "Priority 4"
}
}
}
struct ToDoView: View {
#State private var title: String = ""
#State private var selectedPriority: Priority = .charting
#FocusState private var isTextFieldFocused: Bool
#Environment(\.managedObjectContext) private var viewContext
#FetchRequest(entity: Task.entity(), sortDescriptors: [NSSortDescriptor(key: "dateCreated", ascending: true)]) private var allTasks: FetchedResults<Task>
private func saveTask() {
do {
let task = Task(context: viewContext)
task.title = title
task.priority = selectedPriority.rawValue
task.dateCreated = Date()
try viewContext.save()
} catch {
print(error.localizedDescription)
}
}
private func styleForPriority(_ value: String) -> Color {
let priority = Priority(rawValue: value)
switch priority {
case .one:
return Color.green
case .two:
return Color.red
case .three:
return Color.blue
case .four:
return Color.yellow
default:
return Color.black
}
}
private func updateTask(_ task: Task) {
task.isFavorite = !task.isFavorite
do {
try viewContext.save()
} catch {
print(error.localizedDescription)
}
}
private func deleteTask(at offsets: IndexSet) {
offsets.forEach { index in
let task = allTasks[index]
viewContext.delete(task)
do {
try viewContext.save()
} catch {
print(error.localizedDescription)
}
}
}
var body: some View {
NavigationView {
VStack {
TextField("Enter task...", text: $title)
.textFieldStyle(.roundedBorder)
.focused($isTextFieldFocused)
.foregroundColor(Color(UIColor.systemBlue))
.modifier(TextFieldClearButton(text: $title))
.multilineTextAlignment(.leading)
Picker("Type", selection: $selectedPriority) {
ForEach(Priority.allCases) { priority in
Text(priority.title).tag(priority)
}
}.pickerStyle(.segmented)
Button("Save") {
saveTask()
}
.padding(10)
.frame(maxWidth: .infinity)
.background(Color.blue)
.foregroundColor(.white)
.clipShape(RoundedRectangle(cornerRadius: 10.0, style: .continuous))
List {
ForEach(allTasks) { task in
HStack {
Circle()
.fill(styleForPriority(task.priority!))
.frame(width: 15, height: 15)
Spacer().frame(width: 20)
Text(task.title ?? "")
Spacer()
Image(systemName: task.isFavorite ? "checkmark.circle.fill": "circle")
.foregroundColor(.red)
.onTapGesture {
updateTask(task)
}
}
}.onDelete(perform: deleteTask)
}
Spacer()
}
.padding()
.navigationTitle("To-Do List")
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button(action: {
isTextFieldFocused = false
}) { Text("Done")}
}
}
}
}
}
I'm trying to develop a login page to access to a server using Alamofire. Sending Username and Password the server will return a token. I need to use textfield to let user insert username and password and then save username, password and token in a database using CoreData.
import SwiftUI
import Alamofire
import SwiftyJSON
struct LogInView: View {
#Environment(\.managedObjectContext) var managedObjectContext
#Environment (\.presentationMode) var presentationMode
#State var username : String = ""
#State var password : String = ""
#State var userId : Int = 0
#State var token : String = ""
var body: some View {
NavigationView {
VStack(spacing: 20) {
TextField("Username", text: $username)
.padding()
.background(Color.gray)
.cornerRadius(5.0)
TextField("Password", text: $password)
.padding()
.background(Color.gray)
.cornerRadius(5.0)
rememberForgotView()
Button(action: { self.logIn() })
{
loginButton()
}
Text("\(token)")
Spacer()
}.padding().navigationBarTitle("Log In")
}
}
func logIn() {
let newUser = User(context: self.managedObjectContext)
newUser.username = self.username
newUser.password = self.password
let parameters = ["username": "\($username)", "password": "\($password)"]
AF.request("http://myurl", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON
{
response in
let statusCode = response.response?.statusCode
switch response.result {
case .success(let value):
if let json = value as? [String: Any] {
print(json["Result"] as? Int)
}
case .failure(let error):
print(error)
}
}
}
struct LogInView_Previews: PreviewProvider {
static var previews: some View {
LogInView()
}}
struct loginButton: View {
var body: some View {
VStack {
Text("Log In")
.bold()
.foregroundColor(.white)
.padding(.vertical)
.frame(width: 320)
.background(Color.blue)
.cornerRadius(10.0)
.padding(.top, 20)
}
}}
struct rememberForgotView: View {
var body: some View {
HStack {
Image(systemName: "circle")
.imageScale(.large)
.foregroundColor(.gray)
Text("Remember me")
.font(.footnote)
.foregroundColor(.gray)
Spacer()
Text("Forgot password")
.font(.footnote)
.foregroundColor(.blue)
.bold()
}
}}
Can you help me understanding:
how to return the token and how to save it in my database
how compile "let parameters" with strings from textfield
print eventual errors with a label in the UI
Thank you so much! It's just some weeks that in using Xcode so I'm trying to do my best but I'm not able to find a solution for this problem.
If you know some resources about Alamofire please share.
I have implemented a sheet to edit the values of a client.
It's normally possible to edit the client and close the sheet after pressing the OK-Button. But if the sheet is open for a longer time it is not possible to dismiss the sheet. Nothing happens and they only way to proceed is to quit the program.
Does anyone have an idea why this happens sometimes?
struct ContentView: View {
#State private var showingEditClient = false
var body: some View {
VStack{
HStack {
Button(action: showEditClientSheet) {
Text("Edit Client")
}
.sheet(isPresented: $showingEditClient) {
EditClientSheet()
}
}
}
.frame(minWidth: 400, minHeight: 400)
}
func showEditClientSheet(){
showingEditClient.toggle()
}
}
struct EditClientSheet: View {
#Environment(\.presentationMode) var presentationMode
#State private var name = "Max"
var body: some View {
VStack {
Form {
TextField("Name", text: $name)
}
HStack{
Button(action: cancel) {
Text("Abbrechen")
}
Button(action: editClient) {
Text("Ok")
}
}
}
.frame(minWidth: 200, minHeight: 200)
}
func editClient() {
NSApp.keyWindow?.makeFirstResponder(nil)
//Check if content is correct to save
if name != "" {
//store the changes
self.presentationMode.wrappedValue.dismiss()
}else {
//show Alert
}
}
func cancel() {
self.presentationMode.wrappedValue.dismiss()
}
}