我有一个视图控制器,它具有导航栏和一个表视图。我为什么不能使用界面生成器添加一些标签来在它们之间添加另一个视图?我在youtube上观看了一段视频,该视频讨论了页眉和页脚委托方法,但是当我使用它时,它用我创建的Rect替换了导航栏。
import UIKit
import Foundation
class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate {
final let url = URL(string: "http://www.mildvariety.com/students")
private var students = [Student]()
private var selection = ""
@IBOutlet var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
myTableView.delegate = self
// let headerView = UIView()
// headerView.backgroundColor = UIColor.blue
// headerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 50)
// myTableView.tableHeaderView = headerView
self.loadJson(filename: "students")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "selection"), object: nil, queue: OperationQueue.main) { (notification) in
let popupVc = notification.object as! SortPopupViewController
self.selection = popupVc.optionSelected
print(self.selection)
self.loadJson(filename: "students")
}
}
func loadJson(filename fileName: String) {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let downloadedStudents = try decoder.decode([Student].self, from: data)
// print(jsonData[0].firstName)
self.students = downloadedStudents
if (self.selection == "firstName") {
self.students = students.sorted{$0.firstName < $1.firstName}
}
if (self.selection == "lastName") {
self.students = students.sorted{$0.lastName < $1.lastName}
}
if (self.selection == "year") {
self.students = students.sorted{$0.year < $1.year}
}
if (self.selection == "gpa") {
self.students = students.sorted{$0.gpa < $1.gpa}
}
DispatchQueue.main.async {
self.myTableView.reloadData()
}
} catch {
print("error:\(error)")
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return students.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "StudentCell") as? StudentCell else { return UITableViewCell() }
cell.firstNameLabel.text = students[indexPath.row].firstName
cell.lastNameLabel.text = students[indexPath.row].lastName
cell.yearLabel.text = students[indexPath.row].year
let gpaString:String = String(format:"%.1f", students[indexPath.row].gpa)
cell.gpaLabel.text = gpaString
return cell
}
}
答案 0 :(得分:0)
您可以在原型单元上方添加一个视图(它成为标题),并在下面添加一个视图(成为页脚)。
您已经在原型上方有一个导航栏(这是一个视图)...这就是为什么您只能在其下方添加新视图的原因。
将导航栏添加为表标题视图是很奇怪的。您可能希望将View Controller嵌入到导航控制器中。