将视图拆分为两部分以单独显示

时间:2014-10-10 00:46:39

标签: ios objective-c iphone ios8

我在屏幕上显示的自定义视图中有一个字符串。麻烦的是,它需要被截断,因为没有足够的水平空间来容纳。我想知道是否有可能做到这个古怪的想法尽可能地用文本显示视图,然后去下一个用剩余的文本行显示剩余的视图。

所以基本上,显示ex,一半视图然后显示下面的另一半。有没有办法显示视图的子部分?

2 个答案:

答案 0 :(得分:0)

确定换行符落在何处的一种方法是将字符串放入UILabel(不显示)中,使用与视图相同的字体,并使用sizeThatFits:方法获取文本的显示宽度。如果它小于你的视图宽度,那么你就可以去了,否则从字符串的末尾删除一个字符(或者如果你不想破坏中间字的话),并重复直到它足够小以适应。渲染该字符串并与原始字符串的其余部分重复。

如果字符串可能跨越很多行,那可能会效率低下,所以你可能想要确保在测试显示宽度的字符串中没有太多字符开头(截断为合理的基于视图宽度的数字),或者构建字符串,而不是从末尾截断。

可能还需要调整UILabel上的边缘插入以匹配渲染文本的方式。

答案 1 :(得分:0)

此代码可以让您接近您想要的。我逐字枚举文本,并检查每个子字符串的长度是否适合视图。一旦找到子字符串,我计算字符串的其余部分是什么,将视图的高度调整为这一行文本的高度,并停止枚举。我在故事板中设置为178w x 140h的视图上测试了这个。

#import "ViewController.h"
#import "RDView.h"

@interface ViewController ()
@property (weak,nonatomic) IBOutlet RDView *firstLineView; // the view we're drawing the text into
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightCon; // height constraint for the view we're drawing the first line into
@property (strong,nonatomic) NSString *firstLine;
@property (strong,nonatomic) NSString *restOfLine;
@property (strong,nonatomic) NSDictionary *attribs;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self drawFirstLineOfString:@"This is my pretty long string with extra words" withFont:[UIFont systemFontOfSize:18]];
}

-(void)drawFirstLineOfString:(NSString *) text withFont:(UIFont *) font {
    self.attribs = @{NSFontAttributeName:font};
    __block NSString *lastFragment;
    [text enumerateSubstringsInRange:NSMakeRange(0, text.length) options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        NSString *textFragment = [text substringToIndex:(substringRange.location + substringRange.length)];
        CGRect textRect = [textFragment boundingRectWithSize:CGSizeMake(CGFLOAT_MAX ,CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:self.attribs context:nil];
        if (textRect.size.width >= self.firstLineView.bounds.size.width - 2) { // the -2 is for padding at either end. The string will bedrawn starting at x=1
            self.firstLine = lastFragment;
            self.restOfLine = [text substringFromIndex:substringRange.location];
            self.heightCon.constant = textRect.size.height; // adjust the height of the view to the height of the text
            *stop = YES;
        }
        lastFragment = textFragment;
    }];

    NSLog(@"self.text is:%@",self.firstLine);
    NSLog(@"rest of line is:%@", self.restOfLine);
    self.firstLineView.firstLine = self.firstLine;
    self.firstLineView.attributes = self.attribs;
}

自定义视图具有我在上面最后两行中设置的两个属性,以及.m中的此代码,

- (void)drawRect:(CGRect)rect {
    if (self.firstLine) {
        [self.firstLine drawAtPoint:CGPointMake(1,0) withAttributes:self.attributes];
    }
}
相关问题