2016-12-22 2 views
1

Я - опытный разработчик и разработчик Android и изучаю разработку iPhone на своем MacBook с помощью xCode 8.2, используя книгу «Начало разработки iPhone с помощью Swift 2. Я столкнулся с проблемами, в книге для Swift 3, но были в состоянии справиться с большинством из них.Таблица View Data Source, не показывающая все строки

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

// 
// RootViewController.swift 
// Fonts 
// 
// Created by Thomas Hehl on 12/21/16. 
// 

import UIKit 

class RootViewController: UITableViewController { 

    private var familyNames: [String]! 
    private var cellPointSize: CGFloat! 
    private var favoritesList: FavoritesList! 
    private static let familyCell = "FamilyName" 
    private static let favoritesCell = "Favorites" 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Uncomment the following line to preserve selection between presentations 
     // self.clearsSelectionOnViewWillAppear = false 

     // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
     // self.navigationItem.rightBarButtonItem = self.editButtonItem() 

     familyNames = (UIFont.familyNames as [String]).sorted() 
     let preferredTableViewFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) 
     cellPointSize = preferredTableViewFont.pointSize 
     favoritesList = FavoritesList.sharedFavoritesList 
     tableView.estimatedRowHeight = cellPointSize 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    override func viewWillAppear(_ animated: Bool) { 
     super.viewWillAppear(animated) 
     tableView.reloadData() 
    } 

    func fontForDisplay(atIndexPath indexPath: NSIndexPath) -> UIFont? { 
     if indexPath.section == 0 { 
      let familyName = familyNames[ indexPath.row] 
      let fontName = UIFont.fontNames(forFamilyName: familyName).first 
      return fontName != nil ? UIFont(name: fontName!, size: cellPointSize) : nil 
     } else { 
      return nil 
     } 
    } 

    // MARK: - Table view data source 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     // return the number of sections 
     return favoritesList.favorites.isEmpty ? 1 : 2 
    } 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return section == 0 ? familyNames.count : 1 
    } 

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     return section == 0 ? "All Font Families" : "My Favorite Fonts" 
    } 

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

     if indexPath.section == 0 { 
      // the font names list 
      let cell = tableView.dequeueReusableCell(withIdentifier: RootViewController.familyCell, for: indexPath) 
      cell.textLabel?.font = fontForDisplay(atIndexPath: indexPath as NSIndexPath) 
      cell.textLabel?.text = familyNames[indexPath.row] 
      cell.detailTextLabel?.text = familyNames[indexPath.row] 
      return cell 
     } else { 
      //the favorites list 
      return tableView.dequeueReusableCell(withIdentifier: RootViewController.favoritesCell, for: indexPath) 
     } 
    } 


    /* 
    // Override to support conditional editing of the table view. 
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { 
     // Return false if you do not want the specified item to be editable. 
     return true 
    } 
    */ 

    /* 
    // Override to support editing the table view. 
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete { 
      // Delete the row from the data source 
      tableView.deleteRows(at: [indexPath], with: .fade) 
     } else if editingStyle == .insert { 
      // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
     }  
    } 
    */ 

    /* 
    // Override to support rearranging the table view. 
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { 

    } 
    */ 

    /* 
    // Override to support conditional rearranging of the table view. 
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { 
     // Return false if you do not want the item to be re-orderable. 
     return true 
    } 
    */ 

    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     // Get the new view controller using segue.destinationViewController. 
     // Pass the selected object to the new view controller. 
    } 
    */ 

} 

К сожалению, несмотря на то, что familyNames содержит 75 записей, таблица показывает только первый экранный. Вот скриншот.

Screenshot of Table

Как вы можете видеть, все пути скроллбара в нижней, но это далеко не все шрифты.

+0

Пробовал код, и я вижу все шрифты, используя вертикальную полосу прокрутки. В чем вас беспокоит? –

ответ

0

[EDIT - После чата возникает проблема только в том, что ОП не знает, как прокручивать. OP прислал мне фактический проект, я его запустил, и он отлично работает.]

Ваш код работает нормально. Я буквально только скопировать и вставить код в шаблон Master-Detail, сделал несколько изменений (закомментировать второй раздел вещи, потому что вы не предоставили какой-либо информации о нем), и получил это:

enter image description here

+0

Я использую приложение Single View и изменяю его в соответствии с инструкциями. Есть ли что-то еще, что мне нужно сделать, чтобы получить все данные? Моя полоса прокрутки позволяет мне прокручивать A. – Thom

+0

Или это на iPhone, и это может быть просто симулятор? – Thom

+0

Извините, как я уже сказал, я новичок в этом. Что вам нужно, чтобы посмотреть, как настроить мою раскадровку? Снимок экрана всей настройки раскадровки? Одна из вещей, которые мне не нравятся в этом, это то, что все не сводится к коду, но есть волшебные соединения, которые вы делаете с помощью мыши. – Thom

Смежные вопросы