Мои пользовательские ячейки не отображаются в моем табличном представлении - PullRequest
0 голосов
/ 17 июня 2019

Итак, я пытался заставить свои пользовательские ячейки отображаться в этом виде таблицы, но я не уверен, почему они не отображаются

Я уже проверил другие вопросы о переполнении стека и попытался их исправить, но безрезультатно. Пожалуйста, не обращайте внимания на материал aws, так как вы можете видеть, что у меня есть жестко запрограммированный текст, поэтому я могу просто заставить их появляться на данный момент.

Это код в классе, который содержит табличное представление

 import Foundation
 import AWSDynamoDB
 import AWSCognitoIdentityProvider
 import UIKit
// this will be the main feed class showing the user data 
class UserDetailTableViewController : UITableViewController {
// attributes for the custome cell

@IBOutlet weak var testing: UITextField!

@IBOutlet var Table: UITableView!
var response: AWSCognitoIdentityUserGetDetailsResponse?
var user: AWSCognitoIdentityUser?
var pool: AWSCognitoIdentityUserPool?
var questiondata : Array<Phototext> = Array()


override func viewDidLoad() {
    tableView.delegate = self
    tableView.dataSource = self

    super.viewDidLoad()

    self.pool = AWSCognitoIdentityUserPool(forKey: AWSCognitoUserPoolsSignInProviderKey)
    if (self.user == nil) {
        self.user = self.pool?.currentUser()

    }
         // grabbing data from our aws table
    updateData()

    self.refresh()


}



override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.navigationController?.setToolbarHidden(true, animated: true)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.setToolbarHidden(false, animated: true)
}


@IBAction func Questions(_ sender: Any) {
    performSegue(withIdentifier: "ask", sender: self)
}


// MARK: - IBActions

@IBAction func signOut(_ sender: AnyObject) {
    self.user?.signOut()
    self.title = nil
    self.response = nil
    self.refresh()
}

 // reloads the prior view
 func refresh() {
    self.user?.getDetails().continueOnSuccessWith { (task) ->    
 AnyObject? in
        DispatchQueue.main.async(execute: {
            self.response = task.result
            self.title = self.user?.username
            // saving the user name from the main menu 
            username123 = self.user?.username! ?? "broken"
        })
        return nil
    }


  }
    // function that calls to our aws dynamodb to grab data from the    
     // user     
    //and re update questions
     // the array list

   func updateData(){
    let scanExpression = AWSDynamoDBScanExpression()
    scanExpression.limit = 20
    // testing to grabt the table data upon startup
    let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
    dynamoDBObjectMapper.scan(Phototext.self, expression:     
  scanExpression).continueWith(block: {    
   (task:AWSTask<AWSDynamoDBPaginatedOutput>!) -> Any? in
        if let error = task.error as NSError? {
            print("The request failed. Error: \(error)")
        } else if let paginatedOutput = task.result {
            // passes down an array of object
            for Photo in paginatedOutput.items as! [Phototext] {
                // loading in the arraylist of objects
                // adding the objects to an arraylist
                self.questiondata.append(Photo)




            }

            DispatchQueue.main.async {
                //code for updating the UI

            }

        }

        return ()

    })

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // returning the number of rows
        return 3
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath:     
  IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: 
     "Questionpost", for: indexPath) as! QuestionCell

        cell.QuestionText.text = "call it"
        cell.Subject.text = "a day"

        return cell


    }


}

}

Вот код для класса QuestionCell

import UIKit

class QuestionCell: UITableViewCell {

@IBOutlet weak var Subject: UILabel!

@IBOutlet weak var QuestionText: UITextView!

 }

Класс ячейки называется QuestionCell, а идентификатор, который я оставил в ячейке раскадровки, - Questionpost

Вот фотография моей истории: enter image description here

enter image description here

1 Ответ

0 голосов
/ 17 июня 2019

Я исправил это, объявив расширение с соответствующими типами.

extension UserDetailTableViewController: UITableViewDataSource,UITableViewDelegate{


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // returning the number of rows
    return 3
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Questionpost", for: indexPath) as! QuestionCell

    cell.QuestionText.text = "call it"
    cell.Subject.text = "a day"

    return cell


}}

хорошее объяснение того, что происходит, вы должны соответствовать UITableViewDataSource и UITableViewDelegate, когда вы вставляете представление таблицы.

Избыточное соответствие TableView протоколу UITableViewDataSource с файлами Xib

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...