UITableView 是 iOS 开发中常用的一个控件,用于展示列表数据。UIActivityIndicatorView 是一个用于显示加载状态的控件,通常在数据加载时显示,加载完成后隐藏。
UIActivityIndicatorView 可以提供良好的加载反馈,让用户知道应用正在处理请求。UIActivityIndicatorView 有几种样式可供选择:
UIActivityIndicatorView.Style.largeUIActivityIndicatorView.Style.mediumUIActivityIndicatorView.Style.small在 UITableView 上滚动时 UIActivityIndicatorView 消失的问题通常是由于 UITableView 的复用机制导致的。当 UITableView 滚动时,它会复用不再显示的 cell,这可能会导致 UIActivityIndicatorView 被错误地隐藏或移除。
UITableView 会复用 cell,如果复用的 cell 包含 UIActivityIndicatorView,可能会导致其状态不一致。UIActivityIndicatorView 的布局可能没有正确设置,导致在滚动时被错误地隐藏。创建一个自定义的 cell 类,并在其中管理 UIActivityIndicatorView 的显示和隐藏。
class CustomTableViewCell: UITableViewCell {
let activityIndicator = UIActivityIndicatorView(style: .medium)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupActivityIndicator()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupActivityIndicator() {
contentView.addSubview(activityIndicator)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
])
}
func startAnimating() {
activityIndicator.startAnimating()
}
func stopAnimating() {
activityIndicator.stopAnimating()
}
}在 UITableViewDataSource 中使用自定义 cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
if shouldShowActivityIndicator(for: indexPath) {
cell.startAnimating()
} else {
cell.stopAnimating()
}
return cell
}UITableView 的 contentOffset 监听通过监听 UITableView 的 contentOffset 变化,手动控制 UIActivityIndicatorView 的显示和隐藏。
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
if offsetY > 0 {
activityIndicator.isHidden = true
} else {
activityIndicator.isHidden = false
}
}通过以上方法,可以有效解决在 UITableView 上滚动时 UIActivityIndicatorView 消失的问题。
没有搜到相关的沙龙