【问题标题】:I need to take data from my firebase database and put it into labels, but the data needs to correspond to my tableView cell title我需要从我的 firebase 数据库中获取数据并将其放入标签中,但数据需要与我的 tableView 单元格标题相对应
【发布时间】:2019-04-30 01:28:26
【问题描述】:

我正在构建一个相当简单的应用程序,但遇到了问题。现在我的应用程序有一个主屏幕和一个表格视图,每个单元格中都有一个事件的名称。数据从我的数据库加载到我的单元格中,当您单击单元格时,它会将您带到一个新的视图控制器。我想将特定信息放入与我的活动名称相对应的每个标签中。例如,如果当我单击单元格时读取 STEM Leadership Confrence,我希望三个标签具有匹配的文本:日期、点值和时间范围。任何帮助将不胜感激,谢谢。 (Swift 4 和 Firebase RT 数据库)

import UIKit
import Firebase


var refa: DatabaseReference!

class TableViewController: UITableViewController {
    var posts = [eventStruct]()

    @IBOutlet weak var Tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        refa = Database.database().reference()
        loadNews()
        Tableview?.delegate = self
        Tableview?.dataSource = self

    }
    struct eventStruct {
        let Name: String!
        let date: String!
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "TableToSignUp", sender: self)


    }

    func loadNews() {
        refa.child("Events").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in

            if let valueDictionary = snapshot.value as? [AnyHashable:String]
            {
                let Name = valueDictionary["Name"]
                let date = valueDictionary["date"]
                self.posts.insert(eventStruct(Name: Name, date: date), at: 0)
                self.Tableview.reloadData()


            }
        })
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return posts.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = Tableview.dequeueReusableCell(withIdentifier: "AllEventsCell", for: indexPath)

        //let label1 = cell.viewWithTag(1) as? UILabel
        cell.textLabel?.text = posts[indexPath.row].Name
        //let cell2 = Tableview.dequeueReusableCell(withIdentifier: "AllEventsCell", for: indexPath)



        return cell
}

}

类 ViewController: UIViewController, GIDSignInUIDelegate {

@IBOutlet weak var Nav: UINavigationBar!
@IBOutlet weak var NumOfParticipants: UITextField!
@IBOutlet weak var TimeFrame: UITextField!
@IBOutlet weak var EndDate: UITextField!
@IBOutlet weak var Points: UITextField!
@IBOutlet weak var Create: UIButton!
@IBOutlet weak var ViewAll: UIButton!
@IBOutlet weak var CreateEventButton: UIButton!
@IBOutlet weak var ViewMyEventsButton: UIButton!
@IBOutlet weak var Name: UITextField!
var ref: DatabaseReference?



override func viewDidLoad() {
    super.viewDidLoad()

    CreateEventButton?.layer.cornerRadius = 30
    CreateEventButton?.clipsToBounds = true
    Create?.layer.cornerRadius = 30
    Create?.clipsToBounds = true


    ViewMyEventsButton?.layer.cornerRadius = 30
    ViewMyEventsButton?.clipsToBounds = true


    ViewAll?.layer.cornerRadius = 30
    ViewAll?.clipsToBounds = true

    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().signIn()


    // Do any additional setup after loading the view.
}

@IBAction func CreateEvent(_ sender: Any) {
    let text: String = (Name.text)!
    let date: String = (EndDate.text)!
    let point: String = (Points.text)!
    let timeFrame: String = (TimeFrame.text)!
    let numOfpar: String = (NumOfParticipants.text)!
    ref = Database.database().reference()

    let now = Date()

    let formatter = DateFormatter()

    formatter.timeZone = TimeZone.current

    formatter.dateFormat = "yyyy-MM-dd"


    let dateString = formatter.string(from: now)

    let newUserData = ["Name": text, "date": date, "Point Value": point, "Time Frame": timeFrame, "Volunteers Needed": numOfpar, "Date Created": dateString] as [String: Any]



    ref?.child("Events").childByAutoId().updateChildValues(newUserData)




}


     //,; ["Amount of Points": point];["Date End": date]



}

类 AppDelegate:UIResponder、UIApplicationDelegate、GIDSignInDelegate{

let userDefault  = UserDefaults()

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
    if let error = error{
        print(error.localizedDescription)
        return


    }else{
        let userId = user.userID                  // For client-side use only!
        let idToken = user.authentication.idToken // Safe to send to the server
        let fullName = user.profile.name
        let givenName = user.profile.givenName
        let familyName = user.profile.familyName
        let email = user.profile.email
        let str = email
        let me = str?.count
        let int = (me!-9)
        let secondInt =  (me!-8)
        let XStr = str?.dropFirst(secondInt)
        let NewStr = str?.dropFirst(int)




        guard let authentication = user.authentication else{return}
        let crendential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
        Auth.auth().signInAndRetrieveData(with: crendential) {(result, error)in
            if error == nil {
                self.userDefault.set(true, forKey: "usersignedIn")
                self.userDefault.synchronize()


                 if(NewStr == "gmail.com"){

                    self.window?.rootViewController?.performSegue(withIdentifier: "TeacherSegue", sender: self)
                }

                else if(XStr == "aisd.net"){
                    self.window?.rootViewController?.performSegue(withIdentifier: "TeacherSegue", sender: self)


                }
            }else {
                //self.window?.rootViewController?.performSegue(withIdentifier: "Wegue", sender: self)

                print(error?.localizedDescription ?? "me")
            }
        }




    }


}
var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    // Override point for customization after application launch.
    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self
    return true
}


@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any])
    -> Bool {
        return GIDSignIn.sharedInstance().handle(url,
                                                 sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                                                 annotation: [:])
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return GIDSignIn.sharedInstance().handle(url,
                                             sourceApplication: sourceApplication,
                                             annotation: annotation)
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}


Events-
      -LdK2x1kNMB6fBw0Oorn
      -LdLPGh-_SXIjM7DhjDV
      -LdPVnBYQtAtSOyZM1IR- 
          Date: "2019-04-28"
          Name:"STEM Leadership Confrence"
          Point Value: "12"
          Time Frame: "3-4"

【问题讨论】:

  • 您想在用户触摸您的单元格时更改文本吗?你能添加你的单元格的代码吗?
  • 我不想改变我的单元格的文本,如果这就是你问的只是视图控制器中的标签。我已经为我的所有文件添加了代码,单元格的代码在原始代码中。

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

您需要将信息传递给下一个UIViewController

首先,将您需要的所有信息放入您的 eventStruct 中,并在 Firebase 回调中更新您的结构初始化。

struct EventStruct {
   ...
   var timeFrame: String!
   var points: Int!
}

如果您使用故事板,则需要实现tableView(_:didSelectRowAt:) 方法并使用segue 执行到下一个视图的转换。此链接将帮助您将标识符添加到您的 segue Xcode, where to assign the segue identifier

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let detailToSend: EventStruct = posts[indexPath.row]
    performSegue(withIdentifier: "showDetailSegue", sender: detailToSend)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? ViewController, let detailToSend = sender as? EventStruct {            
        vc.detail = detailToSend
    }
}

如果您使用的是查看代码,则只需要tableView(_:didSelectRowAt:)

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let detailToSend: EventStruct = posts[indexPath.row]
    let vc = ViewController()
    vc.detail = detailToSend
    self.present(vc, animated: true, completion: nil)
}

之后,在ViewControllerviewDidLoad() 中将信息分配给标签。

TimeFrame.text = detail.timeFrame

另一个建议,看看 swift 最佳实践,例如 https://github.com/raywenderlich/swift-style-guide 或在您的项目中使用 SwiftLint。

【讨论】:

  • 我实现了您的更改,但在我的视图中收到错误“使用未解析的标识符 'detail'”确实加载方法和错误“'ViewController' 类型的值没有成员'detail';没有你的意思是‘保留’?”在准备方法中。
  • 我顺便用了segues
  • 你需要在你的ViewController中新建一个var,例如:var detail: EventStruct?
  • 检查值是否达到ViewController in var detail: EventStruct? { didSet { print(detail) } } 或在 prepare(for segue: UIStoryboardSegue, sender: Any?) 的 if 之前和内部放置一个断点。您也可以使用 print(detail) 签入 viewDidLoad。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-22
  • 1970-01-01
相关资源
最近更新 更多