如何实现像NSLineBreakByTruncatingHead为UITextField?(How

2019-10-20 06:10发布

我要实现的东西完全一样NSLineBreakByTruncatingHeadUITextField ,如下所示。 假设原文是:

这是一个不能为UITextField中显示的长文本

我需要它,如:

......不能为UITextField内显示

但现在我得到这样的:

这是长文本不能...

简单地截断开头。 该lineBreakMode属性不是为给定UITextField 。 我怎样才能实现呢?

Answer 1:

我把该解决方案在这里 ,并修改它截断字符串,而不是尾部的头部。 要知道,这只能说明省略号时,现场没有被编辑。

注:该解决方案适用于iOS 7+只。 在iOS 6中使用,使用sizeWithFont:代替sizeWithAttributes:的NSString + TruncateToWidth.m文件。
编辑:针对iOS 6新增支持

的NSString + TruncateToWidth.h

@interface NSString (TruncateToWidth)
- (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font;
@end

的NSString + TruncateToWidth.m

#import "NSString+TruncateToWidth.h"

#define ellipsis @"…"

@implementation NSString (TruncateToWidth)

- (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font
{
    // Create copy that will be the returned result
    NSMutableString *truncatedString = [self mutableCopy];

    // Make sure string is longer than requested width
    if ([self widthWithFont:font] > width)
    {
        // Accommodate for ellipsis we'll tack on the beginning
        width -= [ellipsis widthWithFont:font];

        // Get range for first character in string
        NSRange range = {0, 1};

        // Loop, deleting characters until string fits within width
        while ([truncatedString widthWithFont:font] > width)
        {
            // Delete character at beginning
            [truncatedString deleteCharactersInRange:range];
        }

        // Append ellipsis
        [truncatedString replaceCharactersInRange:NSMakeRange(0, 0) withString:ellipsis];
    }

    return truncatedString;
}

- (CGFloat)widthWithFont:(UIFont *)font
{
    if([self respondsToSelector:@selector(sizeWithAttributes:)])
        return [self sizeWithAttributes:@{NSFontAttributeName:font}].width;
    return [self sizeWithFont:font].width;
}

使用它:

...
// Make sure to import the header file where you want to use it
// assumes instance variable holds your string that populates the field
fieldString = @"abcdefghijklmnopqrstuvwxyz1234567890";
// Size will need to be less than text field's width to account for padding
_myTextField.text = [fieldString stringByTruncatingToWidth:(_myTextField.frame.size.width - 15) withFont:_myTextField.font];
...

// use textFieldShouldBeginEditing to make it animate from the start of the field to the end of the string if you prefer that. I found it a little distracting
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    textField.text = fieldString;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    fieldString = textField.text;
    textField.text = [textField.text stringByTruncatingToWidth:(textField.frame.size.width - 15) withFont:textField.font];

    return YES;
}


文章来源: How to achieve something like NSLineBreakByTruncatingHead for UITextField?