Отображение массива в tableView - PullRequest
0 голосов
/ 11 января 2019

В настоящее время разрабатывается приложение, которое имеет список всех элементов в существующем массиве (который находится в отдельном файле .swift). Это делается с помощью tableView. Тем не менее, я получаю только пустой просмотр таблицы каждый раз. Есть идеи, что пойдет не так?

import UIKit
import MapKit

//Initialize the TableViewController
class CategoriesController: UIViewController, UITableViewDataSource, UITableViewDelegate {

//Retrieve the array
var locationsAll = [Location]()

//Outlet
@IBOutlet var tableView: UITableView!

//Load view
override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return locationsAll.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "allCell") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "allCell")

    let location = locationsAll[indexPath.row]
    cell.textLabel?.text = location.title
    cell.detailTextLabel?.text = location.rating

    return cell
    } 
}

Что касается массива, я использовал структуру. Структура также вызывается из MKMapView.

struct Location {
    let title: String
    let rating: String
    let description: String
    let latitude: Double
    let longitude: Double
}

Файл .swift, содержащий структуру и данные:

struct Location {
        let title: String
        let rating: String
        let description: String
        let latitude: Double
        let longitude: Double
    }

let locations = [
    Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
        Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
        Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111)
]

Я называю это в файле, используя var locationsAll = [Location]() Заранее спасибо!

Ответы [ 3 ]

0 голосов
/ 11 января 2019

Тогда вам нужно

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return locations.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "allCell") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "allCell")

    let location = locations[indexPath.row]
    cell.textLabel?.text = location.title
    cell.detailTextLabel?.text = location.rating

    return cell
    } 
}

как кажется let locations = [ - глобальная переменная, поэтому она доступна везде, или вы можете объявить

var locationsAll = [Location]()

затем в viewDidLoad

locationsAll  = locations 
0 голосов
/ 11 января 2019

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

Вы можете создать местоположения внутри контроллера.

Заменить

var locationsAll = [Location]()

с

var locationsAll = [
    Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
    Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
    Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111)
]

Или объявить местоположения как статическая переменная в структуре

struct Location {
    let title: String
    let rating: String
    let description: String
    let latitude: Double
    let longitude: Double

    static let locations = [
        Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
        Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
        Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111)
    ]
}

и заполнить массив источника данных

var locationsAll = Location.locations
0 голосов
/ 11 января 2019

Число будет равно 0. Поэтому ячейки не отображаются. после добавления данных вам нужно переместить данные на табличное представление.

Полагаю, вы установили ячейку в раскадровке? В противном случае вам необходимо зарегистрировать ячейку перед использованием.

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