XCode:具有不断变化的用途和众多案例的按钮,

问题描述

我是iOS开发/ Xcode的新手,有两个问题。

如果我想让一个按钮根据用户上一页中输入的内容打开页面,例如如果用户输入“农场”,则该按钮将打开带有农场图片的预制情节提要板;如果用户输入“猫”,则该按钮将打开带有猫图片的演示情节提要,依此类推...拉这个吗?

(我知道下一个很常见,因此链接上一篇文章非常好!) 我的第二个问题是,如果有很多类似的情况需要检查,该如何优化应用程序的运行时间?昨晚我下载IDE时,我还不知道Xcode中的语法是否足够使if语句失效,但是我可以根据任何响应来理解通用方法

解决方法

好,这是一个例子

  1. 创建一个ViewController,将其命名为“ FirstVC”
  2. 创建另一个ViewController,将其命名为“ SecondVC”
  3. 创建另一个ViewController,将其命名为“ PictureVC”
  4. 您的资产中有三个名为“农场,狗,猫”的图像。

FirstVc.Swift

class FirstVc.Swift : UIViewController{
           @IBOutlet weak var yourTextField.text : UITextField!

              //You can have textField here or a PickrView Where user select or enter something
                
             //create instance of secondVC which have a string variable named userInput and assign it the value given by the user
            
             // enter name any from "cat","farm","dog"
        
             if let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondVC") as? SecondVC{
                            vc.userInput = yourTextField.text
        
                            // now push that view controller
        
                            self.navigationController?.pushViewController(vc,animated: true)
             }            
       }

SecondVC.Swift

class SecondVC : UIViewController{
               var userInput = ""        
    // this is your ibAction where you will pass the string to pictureVc you got from first vc
    
      @IBAction func buttonTapped(_ sender : Any){
    
        if let vc = self.storyboard?.instantiateViewController(withIdentifier: "PictureVC") as? PictureVC{
                                vc.imageName = userInput
                                self.navigationController?.pushViewController(vc,animated: true)
                                
              }   
          }
      }

PictureVc.Swift

class PictureVc : UIViewController{
            
               var imageName = "" 
               // your imageView     
               @IBOutlet weak var imageView!       
               // set image based on the imageName     
               imageView.image = UIImage(named : imageName)
                             
      }