问题描述
所以我试图以编程方式创建一个 UITableViewCell
以在 UITableView
中使用。我已经完成了所有设置,但是当我加载模拟器时 tableview 是空的。见下面的代码:
class CustomTableViewCell: UITableViewCell {
var firstText = UILabel()
var secondText = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
firstText.translatesAutoresizingMaskIntoConstraints = false
secondText.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(firstText)
contentView.addSubview(secondText)
NSLayoutConstraint.activate([
firstText.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),firstText.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),firstText.heightAnchor.constraint(equalToConstant: 50),firstText.widthAnchor.constraint(equalToConstant: 50)
])
}
override func setSelected(_ selected: Bool,animated: Bool) {
super.setSelected(selected,animated: animated)
// Configure the view for the selected state
}
}
然后是 UITableViewDataSource:
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let person = people[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath) as! CustomTableViewCell
let name = person.value(forKeyPath: "name") as? String
let age = person.value(forKeyPath: "age") as? String
cell.firstText.text = name
cell.secondText.text = age
return cell
}
完整的视图控制器:
class ViewController: UIViewController,UITableViewDelegate {
var names : [String] = []
var people: [NSManagedobject] = []
let TableView = UITableView() // view
override func loadView() {
super.loadView()
setupComponents()
setupTableView()
TableView.delegate = self
TableView.dataSource = self
TableView.register(CustomTableViewCell.self,forCellReuseIdentifier: "cell")
names = ["Samantha","Jacob","Justin"]
}
func setupComponents() {
self.title = "Core Data"
let addButton: UIBarButtonItem = UIBarButtonItem(title: "Add",style: .done,target: self,action: #selector(addTap))
self.navigationItem.rightBarButtonItem = addButton
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
let fetchRequest = NSFetchRequest<NSManagedobject>(entityName: "Person")
let managedContext = appDelegate.persistentContainer.viewContext
//3
do {
people = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error),\(error.userInfo)")
}
}
func setupTableView() {
view.addSubview(TableView)
TableView.translatesAutoresizingMaskIntoConstraints = false
TableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
TableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
TableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
TableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
}
@objc func addTap() {
let alert = UIAlertController(title: "New Friend",message: "Add the name of your friend",preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Add Now",style: .default) { [uNowned self] action in
guard let textField = alert.textFields?.first,let nametoSave = textField.text else { return }
let secondTextField = alert.textFields![1]
let age = secondTextField.text
let ageInt = Int(age!)
self.save(name: nametoSave,age: ageInt!)
self.TableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel",style: .cancel)
alert.addTextField()
alert.addTextField()
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert,animated: true)
}
func save(name: String,age: Int) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
// 1
let managedContext = appDelegate.persistentContainer.viewContext
// 2
let entity = NSEntityDescription.entity(forEntityName: "Person",in: managedContext)!
let person = NSManagedobject(entity: entity,insertInto: managedContext)
// 3
person.setValue(name,forKeyPath: "name")
person.setValue(age,forKeyPath: "age")
// 4
do {
try managedContext.save()
people.append(person)
} catch let error as NSError {
print(error.userInfo)
}
print("People",people)
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(_ tableView: UITableView,for: indexPath) as! CustomTableViewCell
let name = person.value(forKeyPath: "name") as? String
let age = person.value(forKeyPath: "age") as? String
cell.firstText.text = name
cell.secondText.text = age
return cell
}
}
name
和 age
都是有效且有效的,返回的结果并非如此。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)