UILabel visible part of text

前端 未结 2 953
悲&欢浪女
悲&欢浪女 2020-12-01 13:19

Is there a way to get the visible part of text in word wrapped UILabel? I mean exactly the last visible character?

I\'d like to make two labels rounding

2条回答
  •  情书的邮戳
    2020-12-01 13:43

    You could use a category to extend NSString and create the method you mention

    @interface NSString (visibleText)
    
    - (NSString*)stringVisibleInRect:(CGRect)rect withFont:(UIFont*)font;
    
    @end
    
    @implementation NSString (visibleText)
    
    - (NSString*)stringVisibleInRect:(CGRect)rect withFont:(UIFont*)font
    {
        NSString *visibleString = @"";
        for (int i = 1; i <= self.length; i++)
        {
            NSString *testString = [self substringToIndex:i];
            CGSize stringSize = [testString sizeWithFont:font];
            if (stringSize.height > rect.size.height || stringSize.width > rect.size.width)
                break;
    
            visibleString = testString;
        }
        return visibleString;
    }
    
    @end
    

提交回复
热议问题