Я создаю довольно простое приложение и столкнулся с проблемой. Сейчас у моего приложения есть домашний экран и табличное представление с названием события в каждой ячейке. Данные прекрасно загружаются из моей базы данных в мою ячейку, и когда вы нажимаете на ячейку, вы переходите к новому 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"