問題出現在圖片中。 at the top of tableView has some empty area 接口是那個viewController(嵌入在navigationController中)。我把一個tableView放在它上面,然後構造它的約束。但是運行代碼,發生問題。我想嘗試用兩種方法解決它,但是沒有任何變化。tableView的頂部有一些空白區域
self.automaticallyAdjustsScrollViewInsets = true
我將tableView的約束條件調整爲superView,我將top的約束條件設置爲-100,效果很好。 如下面的代碼:
import UIKit
import CoreData
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var people:[NSManagedObject] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "My book"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName:"Person")
do {
people = try managedContext.fetch(fetchRequest)
}catch let error as NSError {
print("Cannot fetch \(error),\(error.userInfo)")
}
}
@IBAction func addName(_ sender: AnyObject) {
let alert = UIAlertController(title: "New name", message: "Add a name", preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in
guard let textField = alert.textFields?.first,
let nameToSave = textField.text else {return
}
self.save(name: nameToSave)
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default)
alert.addTextField()
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert,animated: true)
}
func save(name:String) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)
let person = NSManagedObject(entity: entity!, insertInto: managedContext)
person.setValue(name, forKey: "name")
do {
try managedContext.save()
people.append(person)
}catch let error as NSError {
print("Could not save\(error),\(error.userInfo)")
}
}
}
extension ViewController :UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let person = people[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = person.value(forKey: "name") as? String
return cell
}
}
它不能解決這個問題。相反,它會導致一個新的問題。行消失之間indexPath的行,閃爍點擊行 – MarcSteven