I'm making an app with a viewcontroller that displays two arrays in two different pickerview, an array has the values saved within the application the others are retrieved with rest calls from a rest server. I tried to print the values of the rest server and they are displayed but they are not displayed inside the uipickerview how can I solve this? what is due
class ModificaArticoloMagazzino: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate,UIPickerViewDelegate, UIPickerViewDataSource
{
private var TipologiaUIPicker: UIPickerView = UIPickerView()
private var MagazzinoModUIPicker: UIPickerView = UIPickerView()
private let valori = ["Carico","Scarico","Rimozione","Spostamento"]
private var SetValue:String="Carico"
private var filteredDataMagazzini: [MagazzinoStruct] = []
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
self.view.backgroundColor = UIColor.white
//Caricamento Magazzini
//Caricamento Magazzini
DispatchQueue.main.async {
let mtemp = Magazzino(User: self.u)
mtemp.CaricaMagazzini(completion: { result in
self.filteredDataMagazzini=result
print("\n \n Magazzini caricati: \(result.count)")
//Configurazione Picker View Tipologia Preventivo
self.labelMagazzinoMod = UILabel(frame: CGRect(x: 20, y: 400, width: 120, height: 21))
self.labelMagazzinoMod.font = UIFont(name: "HelveticaNeue-Bold", size: 16.0)
self.labelMagazzinoMod.text = "Magazzino: "
self.view.addSubview(self.labelMagazzinoMod)
self.MagazzinoModUIPicker = UIPickerView(frame: CGRect(x: 150, y: 400, width: 200, height: 50))
self.MagazzinoModUIPicker.delegate = self
self.MagazzinoModUIPicker.dataSource = self
self.MagazzinoModUIPicker.backgroundColor = UIColor.white
self.view.addSubview(self.MagazzinoModUIPicker)
});
}
//Configurazione Picker View Tipologia Preventivo
labelTipologia = UILabel(frame: CGRect(x: 20, y: 270, width: 120, height: 21))
labelTipologia.font = UIFont(name: "HelveticaNeue-Bold", size: 16.0)
labelTipologia.text = "Tipologia: "
self.view.addSubview(labelTipologia)
self.TipologiaUIPicker = UIPickerView(frame: CGRect(x: (self.view.frame.width / 2) - 70, y: 270, width: 200, height: 50))
self.TipologiaUIPicker.delegate = self as UIPickerViewDelegate
self.TipologiaUIPicker.dataSource = self as UIPickerViewDataSource
self.TipologiaUIPicker.backgroundColor = UIColor.white
self.view.addSubview(TipologiaUIPicker)
//Quantita--> labelQuantitaMod e txtQuantita
labelQuantitaMod = UILabel(frame: CGRect(x: 20, y: 220, width: 60, height: 21))
labelQuantitaMod.font = UIFont(name: "HelveticaNeue-Bold", size: 16.0)
labelQuantitaMod.text = "Quantita: "
self.view.addSubview(labelQuantitaMod)
txtQuantita = UITextField(frame: CGRect(x: 120, y: 220, width: 200, height: 21));
txtQuantita.backgroundColor = UIColor.lightGray
txtQuantita.text = "1"
self.view.addSubview(txtQuantita)
}
//Funzione per aggiornare articolo in magazzino
#objc func AggiornaArticoloMagazzino(sender: UIButton!) {
let mtemp = Magazzino(SetArticolo: art, User: u)
if(SetValue=="Carico" || SetValue=="Scarico" || SetValue=="Rimozione"){
mtemp.Aggiorna(Quantita: Int(txtQuantita.text!)!, QuantitaPrecedente: art.Quantita!, IdMagazzino2: 0,Modalita:SetValue, completion: { result in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
if(result==false){
let alertController = UIAlertController(title: "Errore", message: "\(self.SetValue) non riuscito ", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
else{
if(self.SetValue=="Rimozione"){
self.previosScreen()
}
else if(self.SetValue=="Scarico"){
self.art.Quantita=self.art.Quantita!-Int(self.txtQuantita.text!)!
}
else if(self.SetValue=="Carico"){
self.art.Quantita=self.art.Quantita!+Int(self.txtQuantita.text!)!
}
self.labelQuantita.text = "Quantita attuale: \(String(describing: self.art.Quantita!))"
}
});
});
}
else{
mtemp.Aggiorna(Quantita: Int(txtQuantita.text!)!, QuantitaPrecedente: art.Quantita!, IdMagazzino2: 0,Modalita:SetValue, completion: { result in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
if(result==false){
let alertController = UIAlertController(title: "Errore", message: "\(self.SetValue) non riuscito ", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
});
});
}
}
//Questa funzione verifica quale selezione viene effettuata
func CheckSelezione(row: Int){
if(valori[row]=="Carico"){
txtQuantita.isEnabled = true
txtQuantita.isUserInteractionEnabled = true
}
else if(valori[row]=="Scarico"){
txtQuantita.isEnabled = true
txtQuantita.isUserInteractionEnabled = true
}
else if(valori[row]=="Rimozione"){
txtQuantita.isEnabled = false
txtQuantita.isUserInteractionEnabled = false
}
else{
txtQuantita.isEnabled = true
txtQuantita.isUserInteractionEnabled = true
}
SetValue=valori[row]
}
//Funzione per tornare alla schermata principale
func previosScreen(){
let returnView = TabBarViewController()
self.present(returnView, animated: true, completion: nil)
}
#objc func Return(sender: UIButton!) {
previosScreen()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == TipologiaUIPicker {
return valori.count
}
else{
return filteredDataMagazzini.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == TipologiaUIPicker {
CheckSelezione(row: row)
return valori[row]
}
else{
print("\n Nome Magazzino\(filteredDataMagazzini[row].Nome!)")
return filteredDataMagazzini[row].Nome
}
}
}
First of all you need to check result in your API call like how you are getting the data from server. next step is you need to cast your data object into MagazzinoStruct object then you need to append that object into your filteredDataMagazzini array.
Now once you do that you need to reload your MagazzinoModUIPicker pickerview once you complete the first task.
And you need to reload MagazzinoModUIPicker in main queue because you are making an asynchronous call with API.
Related
I solved the problem
override func viewDidLoad() {
super.viewDidLoad()
let save = UserDefaults.standard.bool(forKey: "RememberMe")
self.circleBox.isChecked = save
}
#objc func checkboxvalue(sender: Checkbox) {
if sender.isChecked == true {
labelcheckbox.text = ("Beni")
action((Any).self)
UserDefaults.standard.set(true, forKey:"RememberMe");
}else{
labelcheckbox.text = ("")
UserDefaults.standard.set(false, forKey:"RememberMe");
}
}
I've designed a recall checkbox. But when I log out of the application, I want the checkbox value to be set to UserDefaults as true or false. So I want the checkbox to remember true or false when I get into the application.
lazy var circleBox: Checkbox = {
let squareBox = Checkbox(frame: CGRect(x: 22, y: 290, width: 25, height: 25))
squareBox.tintColor = .black
squareBox.borderStyle = .square
squareBox.checkmarkStyle = .square
squareBox.uncheckedBorderColor = .lightGray
squareBox.borderWidth = 1
squareBox.addTarget(self, action: #selector(checkboxvalue(sender:)), for: .valueChanged)
return squareBox
}()
#objc func checkboxvalue(sender: Checkbox) {
if sender.isChecked == true {
labelcheckbox.text = ("Remember me")
action((Any).self)
}else{
labelcheckbox.text = ("Don't remember")
}
}
I am facing an issue, whenever I going to type in ALTextInputBar() there is a space between keyboard and ALTextInputBar() of 44 points. I don't know from where it is coming. Please have a look on code and image.
#IBOutlet weak var viewChatBox: UIView!
#IBOutlet weak var viewChatBoxBottomConstraint: NSLayoutConstraint!
let textInputBar = ALTextInputBar()
let keyboardObserver = ALKeyboardObservingView()
override func viewDidLoad() {
super.viewDidLoad()
IQKeyboardManager.shared.enable = false
IQKeyboardManager.shared.enableAutoToolbar = false
configureView()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if #available(iOS 11, *) {
// safe area constraints already set
}
else {
if (!(self.topLayoutConstraint != nil)) {
topLayoutConstraint = viewTopBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor)
self.topLayoutConstraint?.isActive = true
}
if (!(self.bottomLayoutConstraint != nil)) {
// bottomLayoutConstraint = viewChatBox.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor)
self.bottomLayoutConstraint?.isActive = true
}
}
}
func configureInputBar () {
btnChat = UIButton(frame: CGRect(x: 0, y: 0, width: 36, height: 36))
keyboardObserver.isUserInteractionEnabled = false
textInputBar.showTextViewBorder = true
textInputBar.leftView = nil
textInputBar.rightView = btnChat
textInputBar.alwaysShowRightButton = true
textInputBar.delegate = self
textInputBar.textView.autocorrectionType = .yes
textInputBar.backgroundColor = UIColor(white: 0.95, alpha: 1)
textInputBar.keyboardObserver = keyboardObserver
viewChatBox.addSubview(textInputBar)
applyConstraintToChatBox()
self.view.layoutIfNeeded()
}
func applyConstraintToChatBox() {
textInputBar.translatesAutoresizingMaskIntoConstraints = false
viewChatBox.translatesAutoresizingMaskIntoConstraints = false
let views = ["textView": textInputBar]
let hConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[textView]-0-|", options: [], metrics: nil, views: views)
let vConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[textView]-0-|", options: [], metrics: nil, views: views)
viewChatBox.addConstraints(hConstraints)
viewChatBox.addConstraints(vConstraints)
}
override var inputAccessoryView: UIView? {
get {
return keyboardObserver
}
}
override var canBecomeFirstResponder: Bool {
return true
}
//MARK: - TEXTVIEW DELEGATE
func textView(textView: ALTextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if (textInputBar.text.count == 0) {
return true
}
let newLength = textInputBar.text.count + text.count - range.length
return (newLength <= 144);
}
func inputBarDidChangeHeight(height: CGFloat) {
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.curveLinear], animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: nil)
}
// MARK: - KEYBOARDS
#objc func keyboardWillChangeFrame(notification: Notification) {
let endFrame = ((notification as NSNotification).userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
viewChatBoxBottomConstraint.constant = view.bounds.height - endFrame.origin.y
print("CHAT BOX FRAME: \(viewChatBox.frame)")
print("TEXT FRAME FRAME: \(textInputBar.frame)")
self.view.layoutIfNeeded()
}
Late answer but may help someone. I had the same issue and found this below code in the documentation.
Only helpful for IQKeyboardManager users.
IQKeyboardManager
self.textField.keyboardDistanceFromTextField = 8; //This will modify default distance between textField and keyboard. For exact value, please manually check how far your textField from the bottom of the page. Mine was 8pt.
Storyboard cutting
The steps that I did were:
Create the + and x buttons in the Controllers
Create simple outlets in the Controllers
Create an action in the Controller for the x (dismiss)-button
#IBAction func button_close_pressed(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
Create a segue on the Storyboard from the + button to the targetViewController.
Create the transition class.
import UIKit
class CircularTransition: NSObject {
var circle = UIView()
var startingPoint = CGPoint.zero {
didSet {
circle.center = startingPoint
}
}
var circleColor = UIColor.red
var duration = 3.0
enum CircularTransitionMode: Int {
case present, dismiss, pop
}
var transitionMode: CircularTransitionMode = .present
}
extension CircularTransition: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
if transitionMode == .present {
if let presentedView = transitionContext.view(forKey: UITransitionContextViewKey.to) {
let viewCenter = presentedView.center
let viewSize = presentedView.frame.size
circle = UIView()
circle.frame = frameForCircle(withViewCenter: viewCenter, size: viewSize, startPoint: startingPoint)
circle.layer.cornerRadius = circle.frame.size.height / 2
circle.center = startingPoint
circle.backgroundColor = circleColor
circle.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
containerView.addSubview(circle)
presentedView.center = startingPoint
presentedView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
presentedView.alpha = 0
containerView.addSubview(presentedView)
UIView.animate(withDuration: duration, animations: {
self.circle.transform = CGAffineTransform.identity
presentedView.transform = CGAffineTransform.identity
presentedView.alpha = 1
presentedView.center = viewCenter
}, completion: { (success: Bool) in
transitionContext.completeTransition(success)
})
}
} else {
let transitionModeKey = (transitionMode == .pop) ? UITransitionContextViewKey.to : UITransitionContextViewKey.from
if let returningView = transitionContext.view(forKey: transitionModeKey) {
let viewCenter = returningView.center
let viewSize = returningView.frame.size
circle.frame = frameForCircle(withViewCenter: viewCenter, size: viewSize, startPoint: startingPoint)
circle.layer.cornerRadius = circle.frame.size.height / 2
circle.center = startingPoint
UIView.animate(withDuration: duration, animations: {
self.circle.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
returningView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
returningView.center = self.startingPoint
returningView.alpha = 0
if self.transitionMode == .pop {
containerView.insertSubview(returningView, belowSubview: returningView)
containerView.insertSubview(self.circle, belowSubview: returningView)
}
}, completion: { (success: Bool) in
returningView.center = viewCenter
returningView.removeFromSuperview()
self.circle.removeFromSuperview()
transitionContext.completeTransition(success)
})
}
}
}
func frameForCircle(withViewCenter viewCenter: CGPoint, size viewSize: CGSize, startPoint: CGPoint) -> CGRect {
let xLength = fmax(startPoint.x, viewSize.width - startPoint.x)
let yLength = fmax(startPoint.y, viewSize.height - startPoint.y)
let offsetVector = sqrt(xLength * xLength + yLength * yLength) * 2
let size = CGSize(width: offsetVector, height: offsetVector)
return CGRect(origin: CGPoint.zero, size: size)
}
}
In the source Controller I added ... to the class
UIViewControllerTransitioningDelegate
Then
let transition = CircularTransition()
And last but not least
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let eventVC = segue.destination as! EventViewController
eventVC.transitioningDelegate = self
eventVC.modalPresentationStyle = .custom
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .present
transition.startingPoint = self.button_addEvent.center
transition.circleColor = self.button_addEvent.backgroundColor!
return transition
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .dismiss
transition.startingPoint = self.button_addEvent.center
transition.circleColor = self.button_addEvent.backgroundColor!
return transition
}
Now, why doesn't that work? I only can think of that the problem comes with the Navigation Controller instead of a normal ViewController, because with a normal one it works fine. But I really have no idea hwo to change the code to match with the Navigation Controller (source Controller).
Kind regards and thank you!
You need to implement UINavigationControllerDelegate in your viewController
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .push:
transition.transitionMode = .present
transition.startingPoint = self.button_addEvent.center
transition.circleColor = self.button_addEvent.backgroundColor!
return transition
default:
transition.transitionMode = .dismiss
transition.startingPoint = self.button_addEvent.center
transition.circleColor = self.button_addEvent.backgroundColor!
return transition
}
}
Here is the code that I tried, but when the image has not loaded yet, nothing show up (an animated indicator should show up). What is the best practice of showing the activity indicator? I hooked into the ASNetworkImageNodeDelegate.
import AsyncDisplayKit
class WideImageFeedNode : ASCellNode, ASNetworkImageNodeDelegate {
var imageNode = ASNetworkImageNode()
var activityIndicator:UIActivityIndicatorView?
init(itemid:Int) {
super.init()
imageNode.backgroundColor = ASDisplayNodeDefaultPlaceholderColor()
let imgURL = URL(string:"http://...somelargeimage.jpg")
imageNode.url = imgURL
imageNode.delegate = self
self.addSubnode(imageNode)
self.automaticallyManagesSubnodes = true
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
var finalStackArr:[ASLayoutElement] = [self.imageNode]
let finalSpec = ASStackLayoutSpec(direction: .vertical, spacing: 10.0, justifyContent: .start, alignItems: .start, children: finalStackArr)
return finalSpec
}
func imageNode(_ imageNode: ASNetworkImageNode, didLoad image: UIImage) {
if let activityIndicator = self.activityIndicator {
activityIndicator.removeFromSuperview()
self.activityIndicator = nil
}
self.setNeedsLayout()
}
// helper functions
func setupActivityIndicator(bounds:CGSize) -> UIActivityIndicatorView {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
var refreshRect = activityIndicator.frame
refreshRect.origin = CGPoint(x: (bounds.width - activityIndicator.frame.size.width) / 2.0, y: (bounds.height - activityIndicator.frame.size.height) / 2.0)
activityIndicator.frame = refreshRect
return activityIndicator
}
func imageNodeDidStartFetchingData(_ imageNode: ASNetworkImageNode) {
self.activityIndicator = setupActivityIndicator(bounds: imageNode.style.preferredSize)
imageNode.view.addSubview(self.activityIndicator!)
}
func imageNode(_ imageNode: ASNetworkImageNode, didFailWithError error: Error) {
if let activityIndicator = self.activityIndicator {
activityIndicator.removeFromSuperview()
self.activityIndicator = nil
}
}
}
Never mind, it works. I was missing one call:
func imageNodeDidStartFetchingData(_ imageNode: ASNetworkImageNode) {
self.activityIndicator = setupActivityIndicator(bounds: imageNode.style.preferredSize)
imageNode.view.addSubview(self.activityIndicator!)
self.activityIndicator!.startAnimating()
}
Hi I'm new to swift and currently I'm working on a project which was done before in swift 2.3 for both iPad and iPhone. My requirement is to use fabric digits framework as to sign up using the mobile number.I did everything as it is in the documentation but the pink color 'login with phone number' button is not appearing in my screen (UIViewController) for some reason. The code is bellow.
import Alamofire
import SwiftyJSON
import DigitsKit
class ViewController: UIViewController, UITextFieldDelegate {
var phoneNum : String?
let movement: CGFloat = 20.0
var phoneHeight: CGFloat = 0.0
var appURLs = AppURLs.sharedInstance
var loadingView: UIView!
var Id: Int!
#IBOutlet weak var username: UITextField!
#IBOutlet weak var activity: UIActivityIndicatorView!
#IBOutlet weak var password: UITextField!
#IBAction func signUpButton(sender: AnyObject) {
let storyboard = switchStoryboards()
let vc = storyboard.instantiateViewControllerWithIdentifier("SignUpViewController")
self.presentViewController(vc, animated: false, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
configureLoadingView()
phoneHeight = self.view.frame.height
UIApplication.sharedApplication().statusBarHidden = true
self.username.delegate = self
self.password.delegate = self
self.slideMenuController()?.removeLeftGestures()
let usernameImageView = UIImageView()
if isIphone() {
usernameImageView.frame = CGRect(x: 0, y: 0, width: 36, height: 20)
} else {
usernameImageView.frame = CGRect(x: 0, y: 0, width: 54, height: 30)
}
usernameImageView.image = UIImage(named: "Username")
view.addSubview(usernameImageView)
username.leftView = usernameImageView
username.leftViewMode = UITextFieldViewMode.Always
let passwordImageView = UIImageView()
if isIphone() {
passwordImageView.frame = CGRect(x: 0, y: 0, width: 36, height: 20)
} else {
passwordImageView.frame = CGRect(x: 0, y: 0, width: 54, height: 30)
}
passwordImageView.image = UIImage(named: "Password")
view.addSubview(passwordImageView)
password.leftView = passwordImageView
password.leftViewMode = UITextFieldViewMode.Always
print("Login view did load loaded")
let authButton = DGTAuthenticateButton(authenticationCompletion: { (session, error) in
if (session != nil) {
// TODO: associate the session userID with your user model
let message = "Phone number: \(session!.phoneNumber)"
let alertController = UIAlertController(title: "You are logged in!", message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: .None))
self.presentViewController(alertController, animated: true, completion: .None)
} else {
NSLog("Authentication error: %#", error!.localizedDescription)
}
})
authButton?.center = self.view.center
self.view.addSubview(authButton!)
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
}
func configureLoadingView() {
loadingView = UIView(frame: CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height))
}
func loginAlerts(messages: String) {
self.activity.stopAnimating()
SwiftSpinner.show("Sign in Failed!", animated: false).addTapHandler({
SwiftSpinner.hide()
}, subtitle: messages)
}
func switchStoryboards() -> UIStoryboard {
switch UIDevice.currentDevice().userInterfaceIdiom {
case .Phone:
// It's an iPhone
return UIStoryboard(name: "Main", bundle: nil)
case .Pad:
return UIStoryboard(name: "StoryboardiPad", bundle: nil)
// It's an iPad
case .Unspecified:
return UIStoryboard(name: "Main", bundle: nil)
// Uh, oh! What could it be?
default:
return UIStoryboard(name: "Main", bundle: nil)
}
}
func isIphone() -> Bool {
switch UIDevice.currentDevice().userInterfaceIdiom {
case .Phone:
// It's an iPhone
return true
case .Pad:
return false
// It's an iPad
case .Unspecified:
return true
// Uh, oh! What could it be?
default:
return true
}
}
}
Okay in such instance all you have to do is to create a custom button in the relevant UI then all will works fine