为什么作者的名字不能在Swift中打印?我是新的在迅速和试图建立一个饲料用户界面使用UIKit,并试图获取API和显示作者姓名与图像在每个tableview单元格,你能帮助我吗?目前它没有显示任何东西,可能是什么问题?
ImageViewController:
import UIKit
class ImageViewController: UITableViewCell {
static let identifier = "ImageTableViewCell"
private let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
imageView.layer.masksToBounds = true
imageView.clipsToBounds = true
return imageView
}()
let authorLabel: UILabel = {
let label = UILabel()
label.textColor = .white
label.font = .systemFont(ofSize: 16)
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "eaeafafa"
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(profileImageView)
contentView.addSubview(authorLabel)
let profileImageConstraints = [
profileImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
profileImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 14),
profileImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -14),
profileImageView.widthAnchor.constraint(equalToConstant: 400),
profileImageView.heightAnchor.constraint(equalToConstant: 200),
]
let authorLabelConstraints = [
authorLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
authorLabel.topAnchor.constraint(equalTo: profileImageView.bottomAnchor, constant: 10)
]
NSLayoutConstraint.activate(authorLabelConstraints)
NSLayoutConstraint.activate(profileImageConstraints)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
FeedImage:
import Foundation
struct FeedImage: Codable, Identifiable {
let id, author: String
let width, height: Int
let url, downloadURL: String
enum CodingKeys: String, CodingKey {
case id, author, width, height, url
case downloadURL = "download_url"
}
}
视图控制器:
import UIKit
class ViewController: UIViewController {
private var viewModel = FeedModel()
private let tableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .systemBackground
tableView.allowsSelection = false
tableView.register(ImageViewController.self, forCellReuseIdentifier: ImageViewController.identifier)
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
private let feedsLabel: UILabel = {
let label = UILabel()
label.text = "Feeds"
label.textColor = .black
label.translatesAutoresizingMaskIntoConstraints = false
label.font = .systemFont(ofSize: 40, weight: .bold)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
view.addSubview(feedsLabel)
viewModel.fetchData()
tableView.delegate = self
tableView.dataSource = self
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: feedsLabel.bottomAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
])
NSLayoutConstraint.activate([
feedsLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 100),
feedsLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20)
])
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.images.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: ImageViewController.identifier, for: indexPath) as? ImageViewController else {
return UITableViewCell()
}
let image = viewModel.images[indexPath.row]
cell.authorLabel.text = image.author
return cell
}
}
饲料型号:
import Foundation
class FeedModel: ObservableObject {
@Published var images = [FeedImage]()
init() {
fetchData()
}
func fetchData() {
let API: String = "https://picsum.photos/v2/list?page=2&limit=100"
guard let url: URL = URL(string: API) else { return }
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error \(error)")
return
}
if let response = response as? HTTPURLResponse {
print("\(response.statusCode)")
return
}
guard let data = data else { return }
do {
let images = try JSONDecoder().decode([FeedImage].self, from: data)
DispatchQueue.main.async {
self.images = images
print("Fetched images with authors:", images)
}
} catch let error {
print(error)
}
}.resume()
}
}
1条答案
按热度按时间vawmfj5a1#
你有很多问题,但没有一个是无法解决的:-)
1.首先,你在FeedModel中有一个不必要的提前返回。响应将始终是
HTTPURLResponse
,因此如果您调用return,则不会处理结果。2.在UIKit中,您必须手动观察数据。因此,即使您的
FeedModel
是ObservableObject
,它也不会通知ViewController有关数据集更改的信息。有多种方法可以解决这个问题,但是如果你的images
数组已经是@Published属性,那么你可以(也必须)订阅它的更改。因此,请将这些添加到viewController中,不要忘记从
viewDidLoad
调用subscribe
函数:3.现在你的代码可以工作了,但我认为会有约束问题。在示例化tableView时可能需要添加
tableView.rowHeight = UITableView.automaticDimension
。另外值得注意的是,作者标签的textColor是白色,因此它可以是与背景颜色相同的颜色。