Подтвердить что ты не робот

Пример UITableView для Swift

Я работаю с Swift и iOS уже несколько месяцев. Я знаком со многими способами, которые делаются, но я недостаточно хорош, чтобы просто писать вещи, не глядя. Я оценил Qaru в прошлом за предоставление быстрых ответов, чтобы вернуть меня в тупик с темами, в которых я ржавый (например, пример для Android AsyncTask).

iOS UITableView входит в эту категорию для меня. Я делал их несколько раз, но я забыл, что это за детали. Я не мог найти другого вопроса в StackOverflow, который просто запрашивает базовый пример, и я ищу что-то меньшее, чем многие из обучающих программ, которые находятся в сети (хотя this один из них очень хорош).

Я предоставляю ответ ниже для моей будущей ссылки и вашей.

4b9b3361

Ответ 1

Пример ниже - адаптация и упрощение более длинного поста от We We Swift. Вот как это будет выглядеть:

enter image description here

Создать новый проект

Это может быть просто обычное приложение Single View.

Добавить код

Замените код ViewController.swift следующим:

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    // Data model: These strings will be the data for the table view cells
    let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]

    // cell reuse id (cells that scroll out of view can be reused)
    let cellReuseIdentifier = "cell"

    // don't forget to hook this up from the storyboard
    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register the table view cell class and its reuse id
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        // (optional) include this line if you want to remove the extra empty cell divider lines
        // self.tableView.tableFooterView = UIView()

        // This view controller itself will provide the delegate methods and row data for the table view.
        tableView.delegate = self
        tableView.dataSource = self
    }

    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.animals.count
    }

    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // create a new cell if needed or reuse an old one
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

        // set the text from the data model
        cell.textLabel?.text = self.animals[indexPath.row]

        return cell
    }

    // method to run when table view cell is tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }
}

Прочитайте комментарии в коде, чтобы увидеть, что происходит. Основные моменты

  • Контроллер представления принимает протоколы UITableViewDelegate и UITableViewDataSource.
  • Метод numberOfRowsInSection определяет, сколько строк будет в табличном представлении.
  • Метод cellForRowAtIndexPath устанавливает каждую строку.
  • Метод didSelectRowAtIndexPath вызывается при каждом didSelectRowAtIndexPath строки.

Добавить табличное представление в раскадровку

Перетащите UITableView на свой View Controller. Используйте автоматическое расположение, чтобы закрепить четыре стороны.

enter image description here

Подключить розетки

Control перетащите из Табличного представления в IB к выходу tableView в коде.

Законченный

Все это. Вы должны быть в состоянии запустить ваше приложение сейчас.

Этот ответ был протестирован с Xcode 9 и Swift 4


вариации

Удаление строк

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

enter image description here

Расстояние между рядами

Если вы хотите иметь расстояние между строками, посмотрите этот дополнительный пример.

enter image description here

Пользовательские ячейки

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

enter image description here

Динамическая высота ячейки

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

enter image description here

Дальнейшее чтение

Ответ 2

Для полноты и для тех, кто не хочет использовать Interface Builder, здесь способ создания той же таблицы, что и в Suragch answer, полностью программно - хотя с другим размером и положением.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    var tableView: UITableView = UITableView()
    let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    let cellReuseIdentifier = "cell"

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.frame = CGRectMake(0, 50, 320, 200)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        self.view.addSubview(tableView)
    }

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!

        cell.textLabel?.text = animals[indexPath.row]

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }

}

Убедитесь, что вы запомнили import UIKit.

Ответ 3

В Swift 4.1 и Xcode 9.4.1

1) Добавьте UITableViewDataSource, UITableViewDelegate, делегированный вашему классу.

2) Создать переменную табличного представления и массив.

3) В viewDidLoad создайте табличное представление.

4) Позвоните представителям таблицы просмотра

5) Вызовите функции делегирования представления таблицы в соответствии с вашими требованиями.

import UIKit
// 1
class yourViewController: UIViewController , UITableViewDataSource, UITableViewDelegate { 

// 2
var yourTableView:UITableView = UITableView()
let myArray = ["row 1", "row 2", "row 3", "row 4"]

override func viewDidLoad() {
    super.viewDidLoad()

    // 3
    yourTableView.frame = CGRect(x: 10, y: 10, width: view.frame.width-20, height: view.frame.height-200)
    self.view.addSubview(yourTableView)

    // 4
    yourTableView.dataSource = self
    yourTableView.delegate = self

}

// 5
// MARK - UITableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return myArray.count
}

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

var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    }
    if self. myArray.count > 0 {
        cell?.textLabel!.text = self. myArray[indexPath.row]
    }
    cell?.textLabel?.numberOfLines = 0

    return cell!
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 50.0
}

Если вы используете раскадровку, нет необходимости в шаге 3.

Но вам нужно создать IBOutlet вашего табличного представления, затем шаг 4.

Ответ 4

//    UITableViewCell set Identify "Cell"
//    UITableView Name is  tableReport

UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet weak var tableReport: UITableView!  

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 5;
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            cell.textLabel?.text = "Report Name"
            return cell;
        }
}

Ответ 5

Вот версия Swift 4.

import Foundation
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{ 
    var tableView: UITableView = UITableView()
    let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    let cellReuseIdentifier = "cell"

    override func viewDidLoad()
    {
        super.viewDidLoad()

        tableView.frame = CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        self.view.addSubview(tableView)
    }

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

    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

        cell.textLabel?.text = animals[indexPath.row]

        return cell
    }

    private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)
    {
        print("You tapped cell number \(indexPath.row).")
    }

}