ios 为什么作者的名字不能在Swift中打印?

yshpjwxd  于 2023-10-21  发布在  iOS
关注(0)|答案(1)|浏览(129)

为什么作者的名字不能在Swift中打印?我是新的在迅速和试图建立一个饲料用户界面使用UIKit,并试图获取API和显示作者姓名与图像在每个tableview单元格,你能帮助我吗?目前它没有显示任何东西,可能是什么问题?
ImageViewController:

  1. import UIKit
  2. class ImageViewController: UITableViewCell {
  3. static let identifier = "ImageTableViewCell"
  4. private let profileImageView: UIImageView = {
  5. let imageView = UIImageView()
  6. imageView.translatesAutoresizingMaskIntoConstraints = false
  7. imageView.contentMode = .scaleAspectFit
  8. imageView.layer.masksToBounds = true
  9. imageView.clipsToBounds = true
  10. return imageView
  11. }()
  12. let authorLabel: UILabel = {
  13. let label = UILabel()
  14. label.textColor = .white
  15. label.font = .systemFont(ofSize: 16)
  16. label.translatesAutoresizingMaskIntoConstraints = false
  17. label.text = "eaeafafa"
  18. return label
  19. }()
  20. override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
  21. super.init(style: style, reuseIdentifier: reuseIdentifier)
  22. contentView.addSubview(profileImageView)
  23. contentView.addSubview(authorLabel)
  24. let profileImageConstraints = [
  25. profileImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
  26. profileImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 14),
  27. profileImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -14),
  28. profileImageView.widthAnchor.constraint(equalToConstant: 400),
  29. profileImageView.heightAnchor.constraint(equalToConstant: 200),
  30. ]
  31. let authorLabelConstraints = [
  32. authorLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
  33. authorLabel.topAnchor.constraint(equalTo: profileImageView.bottomAnchor, constant: 10)
  34. ]
  35. NSLayoutConstraint.activate(authorLabelConstraints)
  36. NSLayoutConstraint.activate(profileImageConstraints)
  37. }
  38. required init?(coder: NSCoder) {
  39. fatalError("init(coder:) has not been implemented")
  40. }
  41. }

FeedImage:

  1. import Foundation
  2. struct FeedImage: Codable, Identifiable {
  3. let id, author: String
  4. let width, height: Int
  5. let url, downloadURL: String
  6. enum CodingKeys: String, CodingKey {
  7. case id, author, width, height, url
  8. case downloadURL = "download_url"
  9. }
  10. }

视图控制器:

  1. import UIKit
  2. class ViewController: UIViewController {
  3. private var viewModel = FeedModel()
  4. private let tableView: UITableView = {
  5. let tableView = UITableView()
  6. tableView.backgroundColor = .systemBackground
  7. tableView.allowsSelection = false
  8. tableView.register(ImageViewController.self, forCellReuseIdentifier: ImageViewController.identifier)
  9. tableView.translatesAutoresizingMaskIntoConstraints = false
  10. return tableView
  11. }()
  12. private let feedsLabel: UILabel = {
  13. let label = UILabel()
  14. label.text = "Feeds"
  15. label.textColor = .black
  16. label.translatesAutoresizingMaskIntoConstraints = false
  17. label.font = .systemFont(ofSize: 40, weight: .bold)
  18. return label
  19. }()
  20. override func viewDidLoad() {
  21. super.viewDidLoad()
  22. view.addSubview(tableView)
  23. view.addSubview(feedsLabel)
  24. viewModel.fetchData()
  25. tableView.delegate = self
  26. tableView.dataSource = self
  27. NSLayoutConstraint.activate([
  28. tableView.topAnchor.constraint(equalTo: feedsLabel.bottomAnchor),
  29. tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
  30. tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  31. tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
  32. ])
  33. NSLayoutConstraint.activate([
  34. feedsLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 100),
  35. feedsLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20)
  36. ])
  37. }
  38. }
  39. extension ViewController: UITableViewDelegate, UITableViewDataSource {
  40. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  41. return self.viewModel.images.count
  42. }
  43. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  44. guard let cell = tableView.dequeueReusableCell(withIdentifier: ImageViewController.identifier, for: indexPath) as? ImageViewController else {
  45. return UITableViewCell()
  46. }
  47. let image = viewModel.images[indexPath.row]
  48. cell.authorLabel.text = image.author
  49. return cell
  50. }
  51. }

饲料型号:

  1. import Foundation
  2. class FeedModel: ObservableObject {
  3. @Published var images = [FeedImage]()
  4. init() {
  5. fetchData()
  6. }
  7. func fetchData() {
  8. let API: String = "https://picsum.photos/v2/list?page=2&limit=100"
  9. guard let url: URL = URL(string: API) else { return }
  10. URLSession.shared.dataTask(with: url) { data, response, error in
  11. if let error = error {
  12. print("Error \(error)")
  13. return
  14. }
  15. if let response = response as? HTTPURLResponse {
  16. print("\(response.statusCode)")
  17. return
  18. }
  19. guard let data = data else { return }
  20. do {
  21. let images = try JSONDecoder().decode([FeedImage].self, from: data)
  22. DispatchQueue.main.async {
  23. self.images = images
  24. print("Fetched images with authors:", images)
  25. }
  26. } catch let error {
  27. print(error)
  28. }
  29. }.resume()
  30. }
  31. }
vawmfj5a

vawmfj5a1#

你有很多问题,但没有一个是无法解决的:-)
1.首先,你在FeedModel中有一个不必要的提前返回。响应将始终是HTTPURLResponse,因此如果您调用return,则不会处理结果。

  1. if let response = response as? HTTPURLResponse {
  2. print("\(response.statusCode)")
  3. return // <- HERE - remove this
  4. }

2.在UIKit中,您必须手动观察数据。因此,即使您的FeedModelObservableObject,它也不会通知ViewController有关数据集更改的信息。有多种方法可以解决这个问题,但是如果你的images数组已经是@Published属性,那么你可以(也必须)订阅它的更改。
因此,请将这些添加到viewController中,不要忘记从viewDidLoad调用subscribe函数:

  1. import Combine
  2. private var cancellables = Set<AnyCancellable>()
  3. private func subscribe() {
  4. viewModel
  5. .$images
  6. .sink { [weak self] _ in
  7. self?.tableView.reloadData()
  8. }
  9. .store(in: &cancellables)
  10. }

3.现在你的代码可以工作了,但我认为会有约束问题。在示例化tableView时可能需要添加tableView.rowHeight = UITableView.automaticDimension。另外值得注意的是,作者标签的textColor是白色,因此它可以是与背景颜色相同的颜色。

展开查看全部

相关问题