Swift - Automatically jump to next text field when not empty - swift

I am working on a game in which the user has to type out the past tense of a verb. My view contains small textfield boxes that only accept one character. As of now I am trying to automatically jump to the next textfield when the former contains a letter.
I want to keep doing this until all the boxes are filled. The user should also be able to go back one box using the return button on the keyboard.
Below is the code I am currently using, but it is not jumping to the next textfield. What am I doing wrong?
var game: Game? {
didSet {
if var answerContent = game?.answer {
let views = (0..<answerContent.characters.count).map { _ in UITextField(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) }
for textField in views {
textField.backgroundColor = UIColor.white
textField.textColor = Constants.MAIN_THEME_COLOR
textField.textAlignment = NSTextAlignment.center
textField.delegate = self
textField.returnKeyType = .next
textField.tag = views.index(of: textField)! + 1
self.container.addArrangedSubview(textField)
views.first?.becomeFirstResponder()
}
}
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let textLength = text.characters.count + string.characters.count - range.length
return textLength <= 1
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
print("Test")
nextField.becomeFirstResponder()
} else {
print("Test2")
textField.resignFirstResponder()
}
return false
}
Updated code (24-04-2017) - Returns nil when trying to jump to the next textField
var game: Game? {
didSet {
if var answerContent = game?.answer {
let views = (0..<answerContent.characters.count).map { _ in UITextField(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) }
for textField in views {
textField.backgroundColor = UIColor.white
textField.textColor = Constants.MAIN_THEME_COLOR
textField.textAlignment = NSTextAlignment.center
textField.delegate = self
textField.addTarget(self, action: #selector(textChanged), for: .editingChanged)
textField.tag = views.index(of: textField)! + 1
self.container.addArrangedSubview(textField)
}
views.first?.becomeFirstResponder()
}
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let textLength = text.characters.count + string.characters.count - range.length
return textLength <= 1
}
func textChanged(sender: UITextField) {
if (sender.text?.characters.count)! > 0 {
print("Entered")
let nextField = textField?.superview?.viewWithTag(textField.tag + 1) as UIResponder!
if (nextField != nil) {
nextField?.becomeFirstResponder()
} else {
print("Error: nil found")
}
} else {
print("Removed")
textField?.resignFirstResponder()
}
}
Answer:
var index: NSInteger = 0
for textField in views {
textField.backgroundColor = UIColor.white
textField.textColor = Constants.MAIN_THEME_COLOR
textField.textAlignment = NSTextAlignment.center
textField.autocapitalizationType = UITextAutocapitalizationType.none
textField.delegate = self
textField.addTarget(self, action: #selector(textChanged), for: .editingChanged)
textField.tag = index
self.container.addArrangedSubview(textField)
index+=1
}
func textChanged(sender: UITextField) {
if (sender.text?.characters.count)! > 0 {
let nextField = sender.superview?.viewWithTag(sender.tag + 1) as UIResponder!
nextField?.becomeFirstResponder()
} else {
sender.resignFirstResponder()
}
}

I suggest that you should add a target to the control event .valueChanged:
// for each text field
textField.addTarget(self, action: #selector(textChanged), for: .valueChanged)
Implement textChanged as follows:
func textChanged(sender: UITextField) {
if sender.text.characters.length > 0 {
let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField
nextField?.becomeFistResponder()
}
}

Follow the code:
import UIKit
// used this to set max characters of UITextField in the storyboard
private var __maxLengths = [UITextField: Int]()
extension UITextField {
#IBInspectable var maxLength: Int {
get {
guard let l = __maxLengths[self] else {
return 150 // (global default-limit. or just, Int.max)
}
return l
}
set {
__maxLengths[self] = newValue
addTarget(self, action: #selector(fix), for: .editingChanged)
}
}
func fix(textField: UITextField) {
let t = textField.text
textField.text = t?.safelyLimitedTo(length: maxLength)
}
}
extension String
{
func safelyLimitedTo(length n: Int)->String {
let c = self.characters
if (c.count <= n) { return self }
return String( Array(c).prefix(upTo: n) )
}
}
class ViewController: UIViewController {
#IBOutlet var input1: UITextField!
#IBOutlet var input2: UITextField!
#IBOutlet var input3: UITextField!
#IBOutlet var input4: UITextField!
#IBOutlet var input5: UITextField!
#IBOutlet var input6: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
setup()
// Do any additional setup after loading the view.
}
func setup() {
input1.tag = 1
input2.tag = 2
input3.tag = 3
input4.tag = 4
input5.tag = 5
input6.tag = 6
input1.addTarget(self, action: #selector(textChanged), for: .editingChanged)
input2.addTarget(self, action: #selector(textChanged), for: .editingChanged)
input3.addTarget(self, action: #selector(textChanged), for: .editingChanged)
input4.addTarget(self, action: #selector(textChanged), for: .editingChanged)
input5.addTarget(self, action: #selector(textChanged), for: .editingChanged)
input6.addTarget(self, action: #selector(textChanged), for: .editingChanged)
}
func textChanged(sender: UITextField) {
if (sender.text?.characters.count)! == 1 {
let nextField = sender.superview?.viewWithTag(sender.tag + 1) as UIResponder!
nextField?.becomeFirstResponder()
} else if (sender.text?.characters.count)! == 0 {
let nextField = sender.superview?.viewWithTag(sender.tag - 1) as UIResponder!
nextField?.becomeFirstResponder()
}
}
}

Update for Swift 4
In viewDidLoad() for each text field,
textField.addTarget(self, action: #selector(textChanged), for: .editingChanged)
Then, add this function,
#objc func textChanged(sender: UITextField) {
if (sender.text?.count)! > 0 {
let nextField = self.view.viewWithTag(sender.tag + 1) as? UITextField
nextField?.becomeFirstResponder()
}
}

Related

UITextView Right Alignment in swift

i am trying text enter in textview right to left alignment but at that time textview starting position enter space not taking textview in swift
#IBOutlet weak var textview: UITextView!
#IBOutlet weak var sampleTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textview.textAlignment = .right
textview.isScrollEnabled = true
textview.heightAnchor.constraint(equalToConstant: 52.0).isActive = true
textview.delegate = self
}
#IBAction func sampleButton(_ sender: Any) {
}
func textViewDidChange(_ textView: UITextView) {
let size = CGSize(width: textView.frame.width, height: 200)
let estimateSize = textView.sizeThatFits(size)
guard textView.contentSize.height < 100.0 else { textview.isScrollEnabled = true; return}
textview.isScrollEnabled = false
textview.constraints.forEach { (constriant) in
if constriant.firstAttribute == .height {
constriant.constant = estimateSize.height
}
}
}
As seen on other posts it has to do with how spaces are handled (). You can add the following delegate code to replace spaces with non breaking spaces :
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText string: String) -> Bool {
if (textView == self.textView) {
let oldString = textView.text!
let newStart = oldString.index(oldString.startIndex, offsetBy: range.location)
let newEnd = oldString.index(oldString.startIndex, offsetBy: range.location + range.length)
let newString = oldString.replacingCharacters(in: newStart..<newEnd, with: string)
textView.text = newString.replacingOccurrences(of: " ", with: "\u{00a0}")
return false;
} else {
return true;
}
}

How to trigger code anytime a UItextfield is empty

I would like to have code for anytime a UItextfield is empty. Not just on the viewdidload but all the time. I tried putting something like if textField.isEmpty == true in the editing changed action although the issue I was having is if you type more than 5 characters and then hold down backspace the code doesn't get triggered. Any ideas for what to do?
Hi you need to subscribe on editing changed 
How to check if the field is empty?
let textField = UITextField()
textField.addTarget(self, action: #selector(textChanged), for: .editingChanged)
#objc func textChanged () {
if textField.text == "" || textField.text == nil {
print("IS EMPTY")
} else {
print("NON EMPTY")
}
}
How to set max length to UITextField
class ViewController: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
let textField = UITextField()
textField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 5
}
}

UITextField is partially hidden by Keyboard when opened

I am attempting to create a collection of UITextField elements. I'd like the next button on the keyboard to skip to the next field and if that field is hidden from view by the keyboard, scroll it into view.
This is my attempt. It works apart from 1 aspect.
When dismissing the keyboard and then selecting another (or the same) field, the text input is partially hidden by the keyboard (see attached gif).
The meat and potatoes is within the ViewController extension.
class ViewController: UIViewController {
var activeField: UITextField?
var lastOffset: CGPoint!
var keyboardHeight: CGFloat!
let scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
let scrollViewContainer: UIStackView = {
let view = UIStackView()
view.axis = .vertical
view.spacing = 10
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(scrollView)
scrollView.addSubview(scrollViewContainer)
let totalFieldCount = 25
for i in 1...totalFieldCount {
let textField = createTextField(self, placeholder: "Field #\(i)", type: .default)
textField.returnKeyType = i < totalFieldCount ? .next : .done
textField.tag = i
scrollViewContainer.addArrangedSubview(textField)
}
NSLayoutConstraint.activate([
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
scrollViewContainer.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
scrollViewContainer.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
scrollViewContainer.topAnchor.constraint(equalTo: scrollView.topAnchor),
scrollViewContainer.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
scrollViewContainer.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
])
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
scrollView.keyboardDismissMode = .interactive
}
func createTextField(_ delegate: UITextFieldDelegate?, placeholder: String, type: UIKeyboardType, isSecureEntry: Bool = false) -> UITextField {
let tf = UITextField(frame: .zero)
tf.placeholder = placeholder
tf.backgroundColor = .init(white: 0, alpha: 0.03)
tf.borderStyle = .roundedRect
tf.font = .systemFont(ofSize: 14)
tf.keyboardType = type
tf.autocapitalizationType = .none
tf.autocorrectionType = .no
tf.isSecureTextEntry = isSecureEntry
tf.heightAnchor.constraint(equalToConstant: 40).isActive = true
if let delegate = delegate {
tf.delegate = delegate
}
return tf
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
activeField = textField
lastOffset = self.scrollView.contentOffset
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1
if let nextResponder = textField.superview?.viewWithTag(nextTag) {
nextResponder.becomeFirstResponder()
} else {
activeField?.resignFirstResponder()
activeField = nil
}
return true
}
}
extension ViewController {
#objc func keyboardWillShow(notification: NSNotification) {
guard keyboardHeight == nil else { return }
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
keyboardHeight = keyboardSize.height
UIView.animate(withDuration: 0.3, animations: {
self.scrollView.contentInset.bottom = self.keyboardHeight
})
guard let activeField = activeField else { return }
let distanceToBottom = self.scrollView.frame.size.height - (activeField.frame.origin.y) - (activeField.frame.size.height)
let collapseSpace = keyboardHeight - distanceToBottom
guard collapseSpace > 0 else { return }
UIView.animate(withDuration: 0.3, animations: {
self.scrollView.contentOffset = CGPoint(x: self.lastOffset.x, y: collapseSpace + 10)
})
}
}
#objc func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: 0.3) {
self.scrollView.contentOffset = self.lastOffset
self.scrollView.contentInset.bottom = 0
}
keyboardHeight = nil
}
}
Replace keyboardFrameBeginUserInfoKey with keyboardFrameEndUserInfoKey

Edit- How can I add that when the answer is wrong it will turn red and green in the correct answer? Swift 4.2

Creates a quiz game
How can I add that when the answer is incorrect, the incorrect answer will turn red and the correct answer will turn green at the same time?
How can I make the colors disappear when the new question comes? I have it that when you press an answer, a new question will come right after that
EDIT: This code is working fine.
#IBOutlet var options: [UIButton]!
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var progressView: UIView!
var allQuestions = QuestionBank()
var Number: Int = 0
var selectedAnswer: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
oppdatertekst()
options.forEach {
$0.layer.cornerRadius = 20
$0.backgroundColor = UIColor.orange
$0.setTitleColor(UIColor.black, for: .normal)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func answerPressed(_ sender: UIButton) {
feedback()
if sender.tag == selectedAnswer {
sender.backgroundColor = UIColor.green
let riktig = NSLocalizedString("Quiz.riktig", comment: "")
ProgressHUD.showSuccess(riktig)
} else if let correctOption = options.first(where: { $0.tag == selectedAnswer }) {
let feilnr = NSLocalizedString("Quiz.feilnr", comment: "")
ProgressHUD.showError("\(feilnr)\(selectedAnswer)")
correctOption.backgroundColor = UIColor.green
sender.backgroundColor = UIColor.red
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.Number += 1
self.oppdatertekst()
}
}
func oppdaterSpm() {
if Number <= allQuestions.list.count - 1{
questionLabel.text = allQuestions.list[Number].question
options.forEach {
$0.backgroundColor = .white
}
options[0].setTitle(allQuestions.list[Number].optionA, for: .normal)
options[1].setTitle(allQuestions.list[Number].optionB, for: .normal)
options[2].setTitle(allQuestions.list[Number].optionC, for: .normal)
options[3].setTitle(allQuestions.list[Number].optionD, for: .normal)
selectedAnswer = allQuestions.list[Number].correctAnswer
} else {
let alert....
}
}
Instead of having four IBOutlets use IBOutletCollection and connect these four buttons to this collection.
In answerPressed method if the correct answer is selected change clicked button color to green. If the wrong answer is selected change selected answer color to red, then get the correct answer button from the collection and change its color to green. After 5 seconds reload next question.
class ViewController: UIViewController {
#IBOutlet var options: [UIButton]!
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var progressView: UIView!
var allQuestions = QuestionBank()
var Number: Int = 0
var selectedAnswer: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
oppdatertekst()
options.forEach {
$0.layer.cornerRadius = 20
$0.backgroundColor = UIColor.orange
$0.setTitleColor(UIColor.black, for: .normal)
}
}
#IBAction func answerPressed(_ sender: UIButton) {
feedback()
if sender.tag == selectedAnswer {
sender.backgroundColor = UIColor.green
let riktig = NSLocalizedString("Quiz.riktig", comment: "")
ProgressHUD.showSuccess(riktig)
} else if let correctOption = options.first(where: { $0.tag == selectedAnswer }) {
let feilnr = NSLocalizedString("Quiz.feilnr", comment: "")
ProgressHUD.showError("\(feilnr)\(selectedAnswer)")
correctOption.backgroundColor = UIColor.green
sender.backgroundColor = UIColor.red
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
Number += 1
oppdatertekst()
}
}
}
Change all buttons color in oppdaterSpm method
func oppdaterSpm() {
if Number <= allQuestions.list.count - 1{
questionLabel.text = allQuestions.list[Number].question
options.forEach {
$0.backgroundColor = .white
}
options[0].setTitle(allQuestions.list[Number].optionA, for: .normal)
options[1].setTitle(allQuestions.list[Number].optionB, for: .normal)
options[2].setTitle(allQuestions.list[Number].optionC, for: .normal)
options[3].setTitle(allQuestions.list[Number].optionD, for: .normal)
selectedAnswer = allQuestions.list[Number].correctAnswer
} else {
let alert....
}
}
You have to write UIButton changes in common method. Call it anywhere.
When New Question Comes:
func whenNewQuestionComes() {
optionA.layer.cornerRadius = 20
optionA.backgroundColor = UIColor.orange
optionA.setTitleColor(UIColor.black, for: .normal)
optionB.layer.cornerRadius = 20
optionB.backgroundColor = UIColor.orange
optionB.setTitleColor(UIColor.black, for: .normal)
optionC.layer.cornerRadius = 20
optionC.backgroundColor = UIColor.orange
optionC.setTitleColor(UIColor.black, for: .normal)
optionD.layer.cornerRadius = 20
optionD.backgroundColor = UIColor.orange
optionD.setTitleColor(UIColor.black, for: .normal)
}
Show Green and Red
#IBAction func answerPressed(_ sender: UIButton) {
feedback()
optionA.backgroundColor = UIColor.red
optionB.backgroundColor = UIColor.red
optionC.backgroundColor = UIColor.red
optionD.backgroundColor = UIColor.red
if sender.tag == selectedAnswer {
sender.backgroundColor = UIColor.green
let riktig = NSLocalizedString("Quiz.riktig", comment: "")
ProgressHUD.showSuccess(riktig)
}
/*
else if let correctOption = options.first(where: { $0.tag == selectedAnswer }) {
let feilnr = NSLocalizedString("Quiz.feilnr", comment: "")
ProgressHUD.showError("\(feilnr)\(selectedAnswer)")
correctOption.backgroundColor = UIColor.green
sender.backgroundColor = UIColor.red
}
*/
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.Number += 1
self.oppdatertekst()
}
}

Tableview doesn't show data on ipad with iOS 9.3 version

I am showing the data on tableview. Everything is working fine on iphone and ipad but data is not showing on ipad with version 9.3.
import UIKit
class AddPatientViewController: UIViewController, UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,UITextFieldDelegate{
#IBOutlet weak var explain: UITextView!
#IBOutlet weak var name: UILabel!
#IBOutlet weak var tblViewAddPatient: UITableView!
#IBOutlet weak var mobile: ZWTextField!
#IBOutlet weak var age: ZWTextField!
#IBOutlet weak var fullname: ZWTextField!
#IBOutlet weak var btnFemale: UIButton!
#IBOutlet weak var btnMale: UIButton!
var gender :String = ""
var username :String = ""
var complain :String = ""
var strLabel = UILabel()
var indicator = UIActivityIndicatorView()
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
var arrComplain = ["-Check-Up","-Teeth Cleaning","-Peroidonatal","-Dental Fillings","-Prothesis","-Extraction","-Hollywoods Smile","-Childrens's Teeth","-Bleaching"]
var arrManaege = ["0","0","0","0","0","0","0","0","0"]
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
explain.delegate = self
let defaults1 = UserDefaults.standard
let user = defaults1.object(forKey: "user") as? NSData
let responseData = NSKeyedUnarchiver.unarchiveObject(with: user! as Data) as? ResponseModel
if responseData != nil {
if responseData?.profile != nil {
username = (responseData?.profile[0].userName)!;
name.text = responseData?.profile[0].userFullName
}
}
mobile.delegate = self
age.delegate = self
fullname.delegate = self
tblViewAddPatient.dataSource = self
tblViewAddPatient.delegate = self
let tapFirstGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard(_:)))
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tapFirstGestureRecognizer)
// Do any additional setup after loading the view.
}
func dismissKeyboard(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" // Recognizes enter key in keyboard
{
textView.resignFirstResponder()
return false
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == fullname {
age.becomeFirstResponder()
} else if textField == age {
mobile.becomeFirstResponder()
} else if textField == mobile {
mobile.resignFirstResponder()
}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func backClick(_ sender: UIButton) {
_ = self.navigationController?.popViewController(animated: true)
}
#IBAction func btnFemaleClicked(_ sender: Any) {
if(btnFemale.isSelected){
}else{
btnFemale.isSelected = true
btnMale.isSelected = false
}
}
#IBAction func btnMaleClicked(_ sender: Any) {
if(btnMale.isSelected){
}else{
btnFemale.isSelected = false
btnMale.isSelected = true
}
}
// Tableview delegates and datasource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrComplain.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tblViewAddPatient.dequeueReusableCell(withIdentifier: "AddPatientTCC") as! AddPatientTCC
cell.selectionStyle = .none
cell.lblTitel.text = arrComplain[indexPath.row]
if (arrManaege[indexPath.row] == "0"){
cell.btnCheckBox.isSelected = false
}else{
cell.btnCheckBox.isSelected = true
}
cell.btnCheckBox.tag = indexPath.row
cell.btnCheckBox.addTarget(self, action: #selector(AddPatientViewController.btnCheckBoxClicked(_:)), for: .touchUpInside)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (arrManaege[indexPath.row] == "0"){
arrManaege[indexPath.row] = "1"
}else{
arrManaege[indexPath.row] = "0"
}
tblViewAddPatient.reloadData()
}
#IBAction func saveClick(_ sender: UIButton) {
if fullname.text!.isEmpty {
showAlerError(titleText: "Error", messagetext: "All fields are Mandatory");
return
}
if age.text!.isEmpty {
showAlerError(titleText: "Error", messagetext: "All fields are Mandatory");
return
}
if mobile.text!.isEmpty {
showAlerError(titleText: "Error", messagetext: "All fields are Mandatory");
return
}
if explain.text!.isEmpty {
showAlerError(titleText: "Error", messagetext: "All fields are Mandatory");
return
}
if btnMale.isSelected == false , btnFemale.isSelected == false {
showAlerError(titleText: "Error", messagetext: "All fields are Mandatory");
return
}
if arrManaege[0] == "0",arrManaege[1] == "0",arrManaege[2] == "0",arrManaege[3] == "0",arrManaege[4] == "0",arrManaege[5] == "0",arrManaege[6] == "0",arrManaege[7] == "0",arrManaege[8] == "0" {
showAlerError(titleText: "Error", messagetext: "All fields are Mandatory");
return
}
if btnFemale.isSelected == true {
gender = "Female"
} else {
gender = "Male"
}
complain = arrManaege[0]+arrManaege[1]+arrManaege[2]+arrManaege[3]+arrManaege[4]+arrManaege[5]+arrManaege[6]+arrManaege[7]+arrManaege[8];
let netowrk = NetworkCall();
if Reachability.isConnectedToNetwork() == true {
self.showLoading(title: "Please wait")
netowrk.addPatient(patientMobile: mobile.text!,patientGender: gender,patientAge: age.text!,patientComplaint: complain,patientExplainComplain: explain.text!,paitentName: fullname.text!,username: username) { responseObject in
self.hideLoading()
if responseObject.status == "true" {
print("Success view controller");
self.showAlerError(titleText: "Success", messagetext: "Patient Added successfully");
} else {
self.showAlerError(titleText: "Error", messagetext: responseObject.message!);
}
return
}
} else {
self.showAlerError(titleText: "Error", messagetext: "Please check Internet connectivity");
}
}
func btnCheckBoxClicked(_ sender: UIButton) {
if (arrManaege[sender.tag] == "0"){
arrManaege[sender.tag] = "1"
}else{
arrManaege[sender.tag] = "0"
}
tblViewAddPatient.reloadData()
}
func textViewDidBeginEditing(_ textView: UITextView)
{
if textView.text == "Explain your compaint"
{
textView.text = ""
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text == ""
{
textView.text = "Explain your compaint"
}
}
func showLoading(title: String) {
strLabel.removeFromSuperview()
indicator.removeFromSuperview()
effectView.removeFromSuperview()
strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
strLabel.text = title
strLabel.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightMedium)
strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 160, height: 46)
effectView.layer.cornerRadius = 15
effectView.layer.masksToBounds = true
indicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
indicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
indicator.startAnimating()
effectView.addSubview(indicator)
effectView.addSubview(strLabel)
view.addSubview(effectView)
}
func hideLoading() {
self.effectView.removeFromSuperview()
//indicator.stopAnimating()
}
func showAlerError(titleText:String,messagetext:String) {
let alertController = UIAlertController(title: titleText, message:
messagetext, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
I am using swift 3.1 but don't know why it is not showing data on iPad with iOS version 9.3 only. Please help me as I an new to swift. I tried all option but nothing is working for me.