gpt4 book ai didi

ios - 我需要从我的 firebase 数据库中获取数据并将其放入标签中,但数据需要与我的 tableView 单元格标题相对应

转载 作者:行者123 更新时间:2023-11-29 05:48:34 42 4
gpt4 key购买 nike

我正在构建一个相当简单的应用程序,但遇到了问题。现在,我的应用程序有一个主屏幕和一个表格 View ,每个单元格中都有一个事件的名称。数据从我的数据库正常加载到我的单元格,当您单击单元格时,它会将您带到一个新的 View Controller 。我想将特定信息放入与我的事件名称相对应的每个标签中。例如,如果当我单击单元格时显示 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"

最佳答案

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

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

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

如果您使用 Storyboard,则需要实现 tableView(_:didSelectRowAt:) 方法并使用 segue 执行到下一个 View 的转换。此链接将帮助您向 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
}
}

如果您使用 View 代码,则只需要 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

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

关于ios - 我需要从我的 firebase 数据库中获取数据并将其放入标签中,但数据需要与我的 tableView 单元格标题相对应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55896704/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com