从自定义tableview单元格获取数据到另一个VC?

时间:2017-12-15 12:00:46

标签: ios swift uitableview uiviewcontroller

寻找一些正确方向的帮助或推动,因为我似乎无法想出这一点。我试图从我在自定义tableview单元格上的电子邮件标签中获取文本到另一个VC,我将有一个联系表单。我在tableview单元格上有一个按钮,所以理想情况下这会进入一个新的VC,我将访问该电子邮件字段,但是对于该特定的单元格。我已经看过使用preparetoseugue函数来为此引入indexpath.row索引,但到目前为止还没有运气。

这是我的自定义tableview单元格:

//
//  RentalCell.swift
//  Login
//
//  Created by George Woolley on 02/12/2017.
//  Copyright © 2017 George Woolley. All rights reserved.
//

import UIKit
import Foundation
import Firebase
import MessageUI

class RentalCell: UITableViewCell, MFMailComposeViewControllerDelegate {
    var rental: Rental!

    @IBOutlet weak var rentalTitleLbl: UILabel!
    @IBOutlet weak var rentalPriceLbl: UILabel!
    @IBOutlet weak var rentalTypeLbl: UILabel!
    @IBOutlet weak var bondLbl: UILabel!
    @IBOutlet weak var rentLbl: UILabel!
    @IBOutlet weak var dateAvalLbl: UILabel!
    @IBOutlet weak var petsLbl: UILabel!
    @IBOutlet weak var descriptionLbl: UILabel!
    @IBOutlet weak var emailField: UILabel!
    @IBOutlet weak var rentalImage: UIImageView!

    func configureCell(rental: Rental, image: UIImage?) {
        self.rental = rental

        self.rentalTitleLbl.text = rental.title
        self.rentalPriceLbl.text = rental.price
        self.rentalTypeLbl.text = rental.rentalType
        self.bondLbl.text = rental.bond
        self.rentLbl.text = rental.price
        self.dateAvalLbl.text = rental.dateAval
        self.petsLbl.text = rental.pets
        self.descriptionLbl.text = rental.description
        self.emailField.text = rental.email

        if image != nil {
            //Image already in cache
            self.rentalImage.image = image
        } else {
            // download image from Firebase
            let ref = Storage.storage().reference(forURL: rental.imageURL!)
            ref.getData(maxSize:  2 * 1024 * 1024, completion: { (data, error) in
                if error != nil {
                    print("An error has occured downloading image")
                } else {
                    print("Image downloaded")
                    if let imageData = data {
                        if let img = UIImage(data: imageData) {
                            self.rentalImage.image = img
                            RentalTableViewVC.imageCache.setObject(img, forKey: rental.imageURL! as NSString)
                        }
                    }
                }
            })
        }
    }
}

这是我的tableViewVC:

//
//  MainVC.swift
//  Login
//

import UIKit
import Firebase
import FirebaseDatabase

class AvertisingVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    @IBOutlet weak var titleField: UITextField!
    @IBOutlet weak var dateAvalField: UITextField!
    @IBOutlet weak var rentalTypeField: UITextField!
    @IBOutlet weak var petsField: UITextField!
    @IBOutlet weak var furnishedField: UITextField!
    @IBOutlet weak var bondField: UITextField!
    @IBOutlet weak var rentField: UITextField!
    @IBOutlet weak var descriptionField: UITextView!
    @IBOutlet weak var addImage: UIImageView!
    @IBOutlet weak var emailField: UITextField!

    var imageSelected = false
    let datePicker = UIDatePicker()
    var imagePicker: UIImagePickerController!
    var databaseRef:DatabaseReference?   //reference to firebase dba
    let rentalTypes = ["Room in shared house", "Entire House","Room Share", "Apartment", "Cottage", "Other"]
    let petsAllowed = ["Yes", "No"]
    let rentalTypePicker = UIPickerView()
    let petsAllowedPicker = UIPickerView()

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return rentalTypes.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return rentalTypes[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        rentalTypeField.text = rentalTypes[row]
        rentalTypeField.resignFirstResponder()
    }

    func createDatePicker() {
        //toolbar
        let toolbar = UIToolbar()
        toolbar.sizeToFit()
        //done button
        let done = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(datePickerDonePressed))
        toolbar.setItems([done], animated: false)
        //add picker to text field
        dateAvalField.inputAccessoryView = toolbar
        dateAvalField.inputView = datePicker
        //format picker for date
        datePicker.datePickerMode = .date
    }

    @objc func datePickerDonePressed() {
        //formate date
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .none
        let dateString = dateFormatter.string(from: datePicker.date)
        dateAvalField.text = "\(dateString)"
        self.view.endEditing(true)
    }

    func setupRentalTypePicker() {
        rentalTypeField.inputView = rentalTypePicker
        rentalTypePicker.dataSource = self
        rentalTypePicker.delegate = self

        rentalTypeField.textAlignment = .center
        rentalTypeField.placeholder = "Select rental type"
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
            addImage.image = image
            imageSelected = true
        } else {
            print("Invalid image from picker")
        }
        imagePicker.dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = true
        imagePicker.delegate = self

        //Firebase Ref
        databaseRef = Database.database().reference().child("Rentals") //can add .child(string:root) to add root dir to dba
        //Date Picker
        createDatePicker()
        //rentalTypePicker
        setupRentalTypePicker()
    }

    @IBAction func backBtnPressed(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }

    @IBAction func submitForm(_ sender: Any) {      // Send data to firebase on submit

        guard let img = addImage.image, imageSelected == true else {

            let alert = UIAlertController(title: "You must upload one image to proceed", message: "It's recommended you upload one image before continuing.", preferredStyle: .alert)

            alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

            self.present(alert, animated: true)

            return
        }

        //Upload image with unique ID as a key
        if let imageData = UIImageJPEGRepresentation(img, 0.2) {

            let imageUID = UUID().uuidString
            let metaData = StorageMetadata()
            metaData.contentType = "image/jpeg"

            DataService.ds.StorageREF.child(imageUID).putData(imageData, metadata: metaData) { (metadata, error) in
                if error != nil {
                    print("Error occured uploading data to firebase")
                } else {
                    print("Successfully uploaded image")

                    let downloadURL = metadata?.downloadURL()?.absoluteString

                    if let url = downloadURL {
                        self.postDataToFirbase(imgURL: url)
                    }
                }
            }
        }

        let alertController = UIAlertController(title: "Success!", message: "You have successfully listed a rental", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "Close Alert", style: .default, handler: nil)
        alertController.addAction(defaultAction)

        present(alertController, animated: true, completion: nil)
    }

    func postDataToFirbase(imgURL: String) {
        let data: Dictionary<String, AnyObject> = [
       "title": titleField.text as AnyObject,
        "price": rentField.text as AnyObject,
        "description": descriptionField.text as AnyObject,
        "bond": bondField.text as AnyObject,
        "date": dateAvalField.text as AnyObject,
        "type": rentalTypeField.text as AnyObject,
        "pets": petsField.text as AnyObject,
        "imageURL": imgURL as AnyObject,
        "email": emailField.text as AnyObject
        ]

        //Post data
        let postDataTo = DataService.ds.DBrefRentals.childByAutoId()
        postDataTo.setValue(data)
        //Clear screen
        titleField.text = ""
        rentField.text = ""
        descriptionField.text = ""
        bondField.text = ""
        rentalTypeField.text = ""
        dateAvalField.text = ""
        petsField.text = ""
        furnishedField.text = ""
        emailField.text = ""
        addImage.image = #imageLiteral(resourceName: "house")
    }

    @IBAction func addImagePressed(_ sender: Any) {
        present(imagePicker, animated: true, completion: nil)
    }
}

1 个答案:

答案 0 :(得分:0)

在&#34; Sender&#34;中声明一个变量类 例: var valueName: String? 接下来是为segue做准备 例如:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.destination is ValuesTableViewController
    {
        let vc = segue.destination as? ValuesTableViewController
        vc?.valueName = "Some string u want to send"
    }
}

其中ValuesTableViewController是Receivers View Controller类

最后要做的是在代码中调用segue方法,你想要将用户重定向到下一个屏幕。

示例:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! UnitTableViewCell
    if let valueName = cell.valueLabel.text {
        print(valueName)
        sendingName = valueName
        if let color = cell.leftColorView.backgroundColor {
            sendingColor = color
        }
        self.performSegue(withIdentifier: "goToValues", sender: self)
    }    
}

如果用户点击TableView中的单元格,您将其重定向到下一个屏幕,这只是一个示例,您也可以在其他情况下使用它。

最后一步:在接收器ViewController中创建一个变量

var valueName: String?

然后你可以在任何你喜欢的地方使用它

快乐编码