0

私は、各セルに1つのUIImageがあり、JSONを使用してAPIからイメージをダウンロードしているUITableViewを持っています。Swiftを使用してUITableView内でUIImage内にActivityIndi​​catorを配置する方法は?

私はバックグラウンドスレッディングを使って最初の画像とデータを処理しました。ただし、ユーザーがテーブルビュー内をスクロールすると、他のセルへの画像のダウンロードが開始されるため、これらのセルには若干のリフレッシュが必要になります。

私はUIImageViewの中にActivityIndi​​catorを追加することを考えました。ユーザーはイメージがダウンロードされていることに気付くでしょう。

追加情報、UIImageViewはUIStackViewの内部にあります。私はisHiddenメソッドについて考えて実装できませんでした。

ありがとうございます。

答えて

1

通常は、Kingfisherのようなライブラリを使用することをお勧めします(読み込み中に表示するプレースホルダビューを設定できると思いますが)手動で行う場合は、

enum LoadingState { 
    case notLoading 
    case loading 
    case loaded(UIImage) 
} 

class MyTableViewCell: UITableViewCell { 
    let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) 
    let imageStackView = UIStackView() 
    let myImageView = UIImageView() // can't be named imageView because UITableViewCell already has one with that name 

    var loadingState: LoadingState = .notLoading { // many ways you could do this, you just need one or more "update" mechanisms to start/stop the spinner and set your image 
     didSet { 
      switch loadingState { 
      case .notLoading: 
       myImageView.image = nil 
       activityIndicator.stopAnimating() 
      case .loading: 
       myImageView.image = nil 
       activityIndicator.startAnimating() 
      case let .loaded(img): 
       myImageView.image = img 
       activityIndicator.stopAnimating() 
      } 
     } 
    } 

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
     super.init(style: style, reuseIdentifier: reuseIdentifier) 
     configure() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     configure() 
    } 

    private func configure() { 
     contentView.addSubview(activityIndicator) 
     contentView.addSubview(imageStackView) 
     imageStackView.addArrangedSubview(myImageView) 
     // constrain activity indicator and stack view 
    } 

    override func prepareForReuse() { 
     super.prepareForReuse() 
     loadingState = .notLoading 
    } 
} 
+0

ありがとうございました。 – sc13

関連する問題