如何将变量从 ViewController 类传递给其他结构?

Posted

技术标签:

【中文标题】如何将变量从 ViewController 类传递给其他结构?【英文标题】:How to pass the variable from a ViewController Class to other Struct? 【发布时间】:2017-09-17 07:23:15 【问题描述】:

我不知道如何将数据从类传递到另一个结构。这是我的 ViewController.swift 文件。我还有另一个名为 Meme.swift 的文件,用于保存结构。我试图将结构放入 ViewController.swift 文件和 Meme.swift 文件中,但我无法访问 topTextField.textlowTextField.text 之类的值并在结构中使用它们。谁能帮我这个? 视图控制器: 导入 UIKit

类 ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate @IBOutlet 弱 var cameraButton: UIBarButtonItem!

@IBOutlet weak var bottomTextField: UITextField!
@IBOutlet weak var topTextField: UITextField!
@IBOutlet weak var imagePickerView: UIImageView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var actionButton: UIBarButtonItem!
let bottomTextFieldDelegate = BottomTextFieldDelegate()

override func viewDidLoad() 
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    topTextField.text = "TOP"
    bottomTextField.text = "BOTTOM"
    topTextField.delegate = self
    bottomTextField.delegate = self.bottomTextFieldDelegate



func textFieldDidBeginEditing(_ textField: UITextField) 
    topTextField.text = ""


func textFieldShouldReturn(_ textField: UITextField) -> Bool 
    self.view.endEditing(true)
    textField.resignFirstResponder()
    actionButton.isEnabled = true
    return true


@IBAction func shareAction(_ sender: Any) 
    let image = generateMemedImage()
    let controller = UIActivityViewController(activityItems: [image as Any], applicationActivities: nil)
    self.present(controller, animated: true, completion: nil)
    controller.completionWithItemsHandler = (activityType: UIActivityType?, completed:Bool, returnedItems:[Any]?, error: Error?) in

        if !completed 
            debugPrint("cancelled")
            return
        else
            self.save()
            self.dismiss(animated: true, completion: nil)
        
    



override func viewWillAppear(_ animated: Bool) 
    super.viewWillAppear(animated)
    cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
    configureTextField(textField: topTextField)
    configureTextField(textField: bottomTextField)
    topTextField.textAlignment = .center
    bottomTextField.textAlignment = .center
    subscribeToKeyboardNotifications()
    actionButton.isEnabled = false



override func viewWillDisappear(_ animated: Bool) 
    super.viewWillDisappear(animated)
    unsubscribeFromKeyboardNotifications()


func configureTextField(textField: UITextField) 
    textField.defaultTextAttributes = memeTextAttributes



func save() -> Meme 
    // Create the meme
    let memedImage = generateMemedImage()
    let meme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, originalImage: imageView.image!, memedImage: memedImage)

    return meme


func generateMemedImage() -> UIImage 

    // TODO: Hide toolbar and navbar
    navigationController?.setToolbarHidden(true, animated: true)
    self.navigationController?.isNavigationBarHidden = true

    // Render view to an image
    UIGraphicsBeginImageContext(self.view.frame.size)
    view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
    let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    // TODO: Show toolbar and navbar
    navigationController?.setToolbarHidden(false, animated: false)
    self.navigationController?.isNavigationBarHidden = false

    return memedImage



func keyboardWillShow(_ notification:Notification) 

    view.frame.origin.y = 0 - getKeyboardHeight(notification)


func keyboardWillHide(_ notification:Notification) 

    view.frame.origin.y = 0 



func getKeyboardHeight(_ notification:Notification) -> CGFloat  //getting the height of keyboard and use it for func keyboardWillShow to relocate
    //the keyboard using keyboardWillShow function

    let userInfo = notification.userInfo
    let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
    return keyboardSize.cgRectValue.height


func subscribeToKeyboardNotifications()  //setting up the obeserver to be notified when keyboard is shown or not, then execute keyboardWillShow function

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)


func unsubscribeFromKeyboardNotifications()  //unsubscribe the notification

    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)

//setting the arributes of the text
let memeTextAttributes:[String:Any] = [
    NSStrokeColorAttributeName: UIColor.black,
    NSForegroundColorAttributeName: UIColor.white,
    NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
    NSStrokeWidthAttributeName: 3,]


@IBAction func pickAnImageFromAlbum(_ sender: Any) 
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary
    present(imagePicker, animated: true, completion: nil)
    


@IBAction func pickAnImageFromCamera(_ sender: Any) 

    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .camera
    present(imagePicker, animated: true, completion: nil)


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage 
        imagePickerView.image = image
        imagePickerView.contentMode = .scaleAspectFit
        dismiss(animated: true, completion: nil)
    



func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
    dismiss(animated: true, completion: nil)

BottomFieldDelegate:

导入基础 导入 UIKit

类BottomTextFieldDelegate:NSObject,UITextFieldDelegate

func textFieldDidBeginEditing(_ textField: UITextField) 
    textField.text = ""


func textFieldShouldReturn(_ textField: UITextField) -> Bool 
    let viewController = ViewController()
    textField.resignFirstResponder()
    viewController.view.endEditing(true)
    let actionButton = viewController.actionButton
    actionButton?.isEnabled = true
    return true

【问题讨论】:

必须是结构体吗? NSObject 不行吗? 它必须是一个结构体 【参考方案1】:

首先你需要将这个函数像 save() 和 generateMemedImage() 移动到你的 ViewController 类中,然后你可以访问 topTextField.text 和 lowTextField.text

像下面这样修改你的结构体,不要把 nsobject 放在结构体中

struct Meme 
    var topText: String
    var bottomText: String
    var memedImage: UIImage
    var originalImage: UIImage

    init(topText: String, bottomText: String, originalImage: UIImage, memedImage: UIImage) 
        self.topText = topText
        self.bottomText = bottomText
        self.originalImage = originalImage
        self.memedImage = memedImage
    

从 Meme 结构中删除 save() 并将该代码放入您的 Viewcontroller 文件中。 修改返回 Meme 结构对象的函数。

func save() -> Meme 
        // Create the meme
        let meme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, originalImage: imageView.image!, memedImage: memedImage)
        return meme   

你可以像下面这样存储在数组中。

let array:[Meme] = []
array.append(save())

【讨论】:

我试图将它放入 ViewController.swift 文件中以检查它是否可以工作,但仍然没有得到我想要的值 @AndyKwok 现在你可以试试这个,我编辑了我的答案,忘了修改你的结构 它显示一个错误并说实例成员 'topTextField' 不能在初始化 meme 的行上的类型 'ViewController' 上使用。 @AndyKwok 你能在你的问题中更新 viewController 类,并显示你是如何初始化的吗? @AndyKwok,哦,我已经告诉过你了,你需要从Meme struct 中删除保存功能并将该代码放入 viewController 文件中。

以上是关于如何将变量从 ViewController 类传递给其他结构?的主要内容,如果未能解决你的问题,请参考以下文章

将数据从 UITableViewCell 传递到 ViewController

如何将 NSMutableArray 传递给另一个 ViewController 类

使用 Delegate 将变量传递回 ViewController 不起作用

将数据从 ViewController 传递到 TabViewController

如何在自定义 UIView 中从 ViewController 传递数据

你如何将数据从 ViewController 传递到包含单独 ViewController 的 PageViewController,然后这些 ViewController 将使用这些数据?