首页 > 解决方案 > 显示可滚动项 Objective-C

问题描述

对于我的应用程序,我有一个 UITextView,当有可滚动内容时我需要显示一个箭头。

当您位于底部或无法滚动文本时,必须隐藏图像。

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

   self.scrollableItem.hidden = YES;
   float scrollViewHeight = scrollView.frame.size.height;
   float scrollContentSizeHeight = scrollView.contentSize.height;
   float scrollOffset = scrollView.contentOffset.y;

   if (scrollOffset > 0 && scrollOffset <= scrollViewHeight / 2) {
    self.scrollableItem.hidden = NO;
   } else if (scrollOffset <= 0 && scrollContentSizeHeight >= scrollViewHeight) {
    self.scrollableItem.hidden = NO;
   }
}

现在这大致可以工作,但我想知道是否有更通用的方法?

谢谢

标签: objective-cscrolluitextview

解决方案


你在正确的轨道上。我们只需要一个公式来描述所需的条件:文本过多,文本超出视图底部

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView != self.textView) return;
    [self updateScrollableItem:(UITextView *)scrollView];
}

- (void)textViewDidChange:(UITextView *)textView {
    [self updateScrollableItem:textView];
}

- (void)updateScrollableItem:(UITextView *)textView {
    CGSize contentSize = textView.contentSize;
    CGSize boundsSize = textView.bounds.size;
    CGFloat contentOffsetY = textView.contentOffset.y;

    BOOL excess = contentSize.height > boundsSize.height;
    // notice the little fudge to make sure some portion of a line is above the bottom
    BOOL bottom = contentOffsetY + textView.font.lineHeight * 1.5 > contentSize.height - boundsSize.height;

    self.scrollableItem.hidden = !excess || bottom;
}

软糖是因为视图高度可能不是给定字体的行高的整数倍。不止一条线似乎可以解决问题。


推荐阅读