【发布时间】:2021-09-21 21:11:35
【问题描述】:
我有一个 ViewController,它使用多个子视图(HomeViewController 等),可以通过我的应用程序底部的自定义标签栏进行选择。在 HomeViewController 内部有一个 UIView,其中包含一个 UITableView,其中包含一个带有名称和图像的 Prototype Custom Cell。
import UIKit
class HomeViewController: UIViewController {
@IBOutlet weak var friendView: UITableView!
let friends = ["batman", "harsh", "ava", "sasha", "fatima", "alfred"]
override func viewDidLoad() {
super.viewDidLoad()
friendView.delegate = self
friendView.dataSource = self
friendView.allowsSelection = false
}
}
extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friends.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = friendView.dequeueReusableCell(withIdentifier: "customCell") as! CustomCell
let friend = friends[indexPath.row]
cell.avatarImg.image = UIImage(named: friend)
cell.nameLbl.text = friend
return cell
}
}
自定义单元格:
import UIKit
class CustomCell: UITableViewCell {
@IBOutlet weak var friendView: UIView!
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var avatarImg: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
当我启动应用程序时,一切看起来都很好。但是,当我开始在表格内滚动时,所有数据突然消失了。故事板和代码之间的所有关系都应该没问题。我认为这可能与我需要使用子视图有关。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tabBarView: UIView!
@IBOutlet weak var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
Design.makeCornersRound(view: tabBarView, radius: 10.0)
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { (timer) in
self.switchToHomeViewController()
}
}
@IBAction func onClickTabBar(_ sender: UIButton) {
let tag = sender.tag
if tag == 1 {
switchToIncomingsViewController()
}
else if tag == 2 {
switchToSpendingsViewController()
}
else if tag == 3 {
switchToHomeViewController()
}
else if tag == 4 {
switchToSavingsViewController()
}
else if tag == 5 {
switchToSettingsViewController()
}
}
func switchToHomeViewController() {
guard let Home = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController else { return }
contentView.addSubview(Home.view)
Home.didMove(toParent: self)
}
...
}
参考我一直在尝试实现的教程:https://www.youtube.com/watch?v=ON3Z0PXSoVk
【问题讨论】:
-
Home.view.frame = contentView.bounds Home.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] 尝试在 contentView.addSubview(Home.view) 之后添加这 2 行并检查它是否有效
-
没有改变任何东西:/
标签: swift uitableview uiviewcontroller storyboard subview