美文网首页
UITableView 添加 subView 一直在其显示内容的

UITableView 添加 subView 一直在其显示内容的

作者: 苍眸之宝宝 | 来源:发表于2020-06-22 10:31 被阅读0次

简介:

有这样一个需求,在数据列表中的底部放置一个提示性的文本或图片,随着数据列表的滚动而滚动,且这个提示性的文本和图片一直在底部(数据列表内容不满手机的一屏时,在底部显示;如果超出一屏,滚动到底部时,提示视图随着数据列表的滚动从底部出现);也就是将提示性的文本和图片放在UITableView的显示内容的底部。


半屏.gif 满屏.gif

实现思路:

将提示的文本和图片视图作为子View添加到 UITableView 的底部,设置 UITableView 的 tableFooterView 的 View 的尺寸和提示的文本和图片视图尺寸相同;UITableView contentSize 变动时,修改提示的文本和图片视图的 y 值,使其一直居于 UITableView 的 contentView 的底部。

代码实现:

UITableView 和提示的文本和图片视图的初始化和布局。

        let tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.estimatedRowHeight = 98
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.frame = CGRect.init(x: 0, y: kNavigationHeight, width: kScreenWidth, height: kScreenHeight - kNavigationHeight)
        self.view.addSubview(tableView)
        
        tableView.tableFooterView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: (32 + kBottomSafeMargin)))

        let tipView = UIView.init()
        tipView.frame = CGRect.init(x: 0, y: (kScreenHeight - kNavigationHeight - 32 - kBottomSafeMargin), width: kScreenWidth, height: 32 + kBottomSafeMargin)
        tableView.addSubview(tipView)
        tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)

UITableView contentSize 变动时,设置提示的文本和图片视图的 y 值。

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let key = keyPath, let value = change?[.newKey] else {
            return
        }
        if key == "contentSize" {
            let tableViewH = self.tableView?.height ?? 0
            let contentH = (value as? CGSize)?.height ?? 0
            NSLog("contentSize=\(value)")
            if contentH <= tableViewH {
                self.footerView?.y = (kScreenHeight - kNavigationHeight - (32 + kBottomSafeMargin))
            }
            else {
                self.footerView?.y = (contentH - (32 + kBottomSafeMargin))
            }
        }
    }
    
    deinit {
        self.tableView?.removeObserver(self, forKeyPath: "contentSize")
    }

相关文章

网友评论

      本文标题:UITableView 添加 subView 一直在其显示内容的

      本文链接:https://www.haomeiwen.com/subject/ocotfktx.html