ios - 如何滚动到属性字符串的特定部分

标签 ios uiscrollview nsattributedstring

我有一个位于 UIScrollView 内的 NSMutableAttributedString。我使用 addAttributes:range: 突出显示字符串的一部分功能。

当存在大量文本时,我目前必须手动滚动很多方式才能到达突出显示的部分。我想想出一种方法,让 View 在加载 View 时自动滚动到突出显示的部分 - 类似于如何使用 anchors to link to a specific part of a webpage .

我猜有一个函数,给定某种数字将允许我滚动到页面的特定部分?我怎样才能得出这样的数字来提供这样的功能?使用属性字符串中的 NSRange 组件?

也许有更好的方法来实现这一点?

最佳答案

UIScrollView 具有方法 setContentOffset:animated:,它允许您滚动到内容中的特定点。要确定适当的偏移量是多少,您必须确定突出显示部分之前的属性字符串部分的宽度。用于执行此操作的方法的文档 can be found here .您可以使用 NSAttributedStringsize 方法来完成此操作。

它看起来像这样:

@interface SomeViewController : UIViewController
@end

@implementation SomeViewController {
    UIScrollView* _scrollView;
}

- (void)scrollToOffset:(NSInteger)offset inAttributedString:(NSAttributedString*)attributedString {
    NSAttributedString* attributedSubstring = [attributedString attributedSubstringFromRange:NSMakeRange(0, offset)];
    CGFloat width = attributedSubstring.size.width;
    [_scrollView setContentOffset:CGPointMake(width, 0.0f) animated:YES];
}
@end

上面的代码假设我们正在讨论单行文本并且水平滚动。或者,要对环绕到任意高度的固定宽度执行此操作,您需要使用以下代码(而不是 attributeSubstring.size.height)计算高度,然后可能减去一点以考虑要显示的最后一行子字符串:

    CGFloat height = [attributedSubstring boundingRectWithSize:CGSizeMake(<#fixed width to wrap at#>, HUGE_VALF) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;
    [_scrollView setContentOffset:CGPointMake(0.0f, height) animated:YES];

这类似于我在确定具有需要容纳的动态文本的表或 Collection View 单元格的高度时使用的代码。

关于ios - 如何滚动到属性字符串的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18177726/

相关文章:

iOS 为什么不能方法 collectionView :didSelectItemAtIndexPath: be called from UITapGestureRecognizer?

ios - 覆盖 View 随着 UITableView 的滚动而滚动

objective-c - 如何在 UIRefreshControl 中使用 NSAttributedString

iphone - iPhone 推送通知是通过 HTTP 还是 HTTPS 发送的?

ios - uitextview 周围的自定义边框

ios - 如何根据 UITableView 高度动态设置 UIScrollView 高度?

objective-c - 测量 cocoa 中的绳子高度

ios - 更改属性文本字体大小并保留格式

ios - 确定按钮背景图像 - Objective-C (Xcode)

ios - UILabel 找到适合宽度的高度