首页 > 解决方案 > 滚动视图滚动时如何检查视图可滚动位置

问题描述

我们已经通过使用文本视图实现了粘性流广告功能。当文本视图滚动时,我们显示在文本视图文本中间添加了一个视图。当 textview 滚动和添加的视图从视图中消失时。然后我们展示了另一个与添加的视图内容相同的视图。它工作完美。但是现在我的新要求是当用户滚动文本视图并添加视图时。然后我们需要根据视图外观显示第二个添加的视图。就像添加的视图只有 50% 出现在屏幕上,那么我们需要显示第二个视图。现在我的问题是如何根据滚动位置检测视图外观。用于隐藏或显示视图。提前致谢

标签: iosswifttextviewuiscrollview

解决方案


您必须为此使用scrollViewDidScroll委托方法。您可以尝试以下方法:

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    // Table View Scroll Image
    let viewContentOffset = textview.contentOffset
    let viewContentSize = textview.contentSize
    let viewBounds = textview.bounds.size

    // Use Alpha value to manipulation
    let bottomOffset = scrollView.contentSize.height - scrollView.bounds.size.height
    let alpha = (scrollView.contentOffset.y / bottomOffset) * 2
}

使用 NSAttributtedString 将图像添加到 TextView:

textView.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda."
let image = UIImage(named: "sampleImage.png");
let attachment = NSTextAttachment()
attachment.image = image
let attString = NSAttributedString(attachment: attachment)
textView.textStorage.insert(attString, at: textView.text.count/2)

推荐阅读