我在mvvm做。
我的代码如下: -
private var url = URL(字符串:" http://www.example.com")! typealias JSONDictionary = [String:Any]
yum group install "My Group"
我的旅馆模型: -
class hostelmodel:NSObject {
class Webservice{
static func fetchHostels(completion: @escaping ([JSONDictionary]) -> ()) {
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data {
let json = try! JSONSerialization.jsonObject(with: data, options: [])
let dictionaries = json as! [JSONDictionary]
completion(dictionaries)
}
}.resume()
}
}
}
我的hostelviewmodel: -
var name: String?
var city: String?
init(_ dictionary: [String: Any]) {
if let name = dictionary["name"] as? String, let location = dictionary["location"] as? [String: Any], let city = location["city"] as? String {
self.name = name
self.city = city
}
}
我的hostablecell: -
class hostelviewmodel: NSObject {
private var hostels: [hostelmodel] = []
func fetchData(completion: (() -> Void)?) {
Webservice.fetchHostels { [weak self] dictionaries in
self?.hostels = dictionaries.flatMap(hostelmodel.init)
completion?()
}
}
func numberOfSections() -> Int {
//your number of section
return 1
}
func numberOfRows() -> Int {
//your number of rows
return hostels.count
}
func hostel(atIndex index: Int) -> hostelmodel {
return hostels[index]
}
}
my hostellist:-
@IBOutlet private weak var tableView: UITableView!
private var viewModel: hostelviewmodel
init(hostelViewModel: hostelviewmodel) {
self.viewModel = hostelViewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
private func fetchData() {
viewModel.fetchData { [weak self] in
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRows()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)as! QM_RestaurtantCell
cell.setRestaurtantData(restaurtant: QM_RestaurtantModel)
return cell
}
}
}
我没有故事板,所以在这里如何设置appdelegate。我应该在app delegate类中将其设置为根视图控制器。以及如何在swift中的行索引的tableview单元格中显示名称和城市值。如何去除
答案 0 :(得分:0)
迁移到App Delegate到您的HostelList视图控制器:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Transferring Control to First Controller
window = UIWindow(frame: UIScreen.main.bounds)
let nav1 = UINavigationController()
let vc = HostelList()
nav1.viewControllers = [vc]
window?.rootViewController = vc
window?.makeKeyAndVisible()
return true
}
要在tableview中设置值,请使用此功能:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
}
答案 1 :(得分:-1)
确定。试试这个重构的代码: AppDelegate didFinish: func应用程序(_ application:UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let vm = HostelViewModel()
let vc = HostelViewController(hostelViewModel: vm)
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = vc
window?.makeKeyAndVisible()
return true
}
<强> HostelViewController:强>
class HostelViewController: UIViewController {
private let tableView = UITableView(frame: .zero, style: .plain)
private var viewModel: HostelViewModel
init(hostelViewModel: HostelViewModel) {
self.viewModel = hostelViewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
createUI()
tableView.dataSource = viewModel
fetchData()
}
func createUI() {
tableView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(tableView)
tableView.register(HostelCell.self, forCellReuseIdentifier: cellIdentifier)
tableView.estimatedRowHeight = 60
tableView.rowHeight = UITableViewAutomaticDimension
let tableViewConstraints: [NSLayoutConstraint] = [
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
]
NSLayoutConstraint.activate(tableViewConstraints)
}
private func fetchData() {
viewModel.fetchData { [weak self] in
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
}
}
<强> HostelViewModel:强>
class HostelViewModel: NSObject, UITableViewDataSource {
private var hostels: [HostelModel] = []
func fetchData(completion: (() -> Void)?) {
Webservice.fetchHostels { [weak self] dictionaries in
self?.hostels = dictionaries.flatMap(HostelModel.init)
completion?()
}
}
func hostel(atIndex index: Int) -> HostelModel {
return hostels[index]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return hostels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let hostel = hostels[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! HostelCell
cell.setRestaurtantData(restaurtant: hostel)
return cell
}
}
HostelCell文件:
let cellIdentifier = "HostelTableCell"
class HostelCell: UITableViewCell {
private var name: UILabel = UILabel()
private var city: UILabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
createUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setRestaurtantData(restaurtant: HostelModel)
{
self.name.text = restaurtant.name
self.city.text = restaurtant.city
}
func createUI() {
[city, name].forEach {
contentView.addSubview($0)
$0.translatesAutoresizingMaskIntoConstraints = true
}
city.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8).isActive = true
city.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
name.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8).isActive = true
name.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
}
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
}
}
<强> HostelModel:强>
class HostelModel {
var name: String?
var city: String?
init(_ dictionary: [String: Any]) {
if let name = dictionary["name"] as? String, let location = dictionary["location"] as? [String: Any], let city = location["city"] as? String {
self.name = name
self.city = city
}
}
}