iOS7 TextKit:项目符号对齐

20

我正在为iOS 7编写一个应用程序,并尝试在不可编辑的UITextView中获得良好的项目符号格式。

插入一个项目符号字符很容易,但是左缩进当然不会跟随。在iOS 7上设置一个项目符号后面的左缩进最简单的方法是什么?

谢谢!

Frank


  • 在项目中添加制表符。
- Shmidt
1
我的意思是整个多行段落的缩进,而不仅仅是第一行。 - Frank R.
8个回答

46

所以我看了一下,这里是从邓肯的答案中提取出来的最小代码,可以使其正常工作:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:yourLabel.text];

NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
[paragrahStyle setParagraphSpacing:4];
[paragrahStyle setParagraphSpacingBefore:3];
[paragrahStyle setFirstLineHeadIndent:0.0f];  // First line is the one with bullet point
[paragrahStyle setHeadIndent:10.5f];    // Set the indent for given bullet character and size font

[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle
                         range:NSMakeRange(0, [self.descriptionLabel.text length])];

yourLabel.attributedText = attributedString;

这是我应用程序的结果:

Quadratic Master


9
以下是我用来设置带项目符号的段落的代码。这个代码来自于一个工作中的应用程序,并用于在用户点击格式化按钮后将样式应用于整个段落。我试图放入所有依赖方法,但可能会漏掉一些。
请注意,我将大多数缩进设置为厘米,因此在列表末尾使用了转换函数。
我还检查了制表符是否存在(iOS上没有制表键!),并自动插入破折号和制表符。
如果您只需要段落样式,请查看下面几个方法,其中设置了firstLineIndent等。
请注意,所有这些调用都包含在[textStorage beginEditing/endEditing]中。尽管下面有(IBAction),但该方法不是直接由UI对象调用的。
        - (IBAction) styleBullet1:(id)sender
        {
            NSRange charRange = [self rangeForUserParagraphAttributeChange];
            NSTextStorage *myTextStorage = [self textStorage];

            // Check for "-\t" at beginning of string and add if not found
            NSAttributedString *attrString = [myTextStorage attributedSubstringFromRange:charRange];
            NSString *string = [attrString string];

            if ([string rangeOfString:@"\t"].location == NSNotFound) {
                NSLog(@"string does not contain tab so insert one");
                NSAttributedString * aStr = [[NSAttributedString alloc] initWithString:@"-\t"];
                // Insert a bullet and tab
                [[self textStorage] insertAttributedString:aStr atIndex:charRange.location];

            } else {
                NSLog(@"string contains tab");
            }

            if ([self isEditable] && charRange.location != NSNotFound)
            {
                [myTextStorage setAttributes:[self bullet1Style] range:charRange];
            }
        }

        - (NSDictionary*)bullet1Style
        {
            return [self createStyle:[self getBullet1ParagraphStyle] font:[self normalFont] fontColor:[UIColor blackColor] underlineStyle:NSUnderlineStyleNone];

        }

        - (NSDictionary*)createStyle:(NSParagraphStyle*)paraStyle font:(UIFont*)font fontColor:(UIColor*)color underlineStyle:(int)underlineStyle
        {
            NSMutableDictionary *style = [[NSMutableDictionary alloc] init];
            [style setValue:paraStyle forKey:NSParagraphStyleAttributeName];
            [style setValue:font forKey:NSFontAttributeName];
            [style setValue:color forKey:NSForegroundColorAttributeName];
            [style setValue:[NSNumber numberWithInt: underlineStyle] forKey:NSUnderlineStyleAttributeName];

            FLOG(@" font is %@", font);

            return style;
        }

        - (NSParagraphStyle*)getBullet1ParagraphStyle
        {
            NSMutableParagraphStyle *para;
            para = [self getDefaultParagraphStyle];
            NSMutableArray *tabs = [[NSMutableArray alloc] init];
            [tabs addObject:[[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft location:[self ptsFromCMF:1.0] options:nil]];
            //[tabs addObject:[[NSTextTab alloc] initWithType:NSLeftTabStopType location:[self ptsFromCMF:1.0]]];
            [para setTabStops:tabs];
            [para setDefaultTabInterval:[self ptsFromCMF:2.0]];
            [para setFirstLineHeadIndent:[self ptsFromCMF:0.0]];
            //[para setHeaderLevel:0];
            [para setHeadIndent:[self ptsFromCMF:1.0]];
            [para setParagraphSpacing:3];
            [para setParagraphSpacingBefore:3];
            return para;
        }
    - (NSMutableParagraphStyle*)getDefaultParagraphStyle
    {
        NSMutableParagraphStyle *para;
        para = [[NSParagraphStyle defaultParagraphStyle]mutableCopy];
        [para setTabStops:nil];
        [para setAlignment:NSTextAlignmentLeft];
        [para setBaseWritingDirection:NSWritingDirectionLeftToRight];
        [para setDefaultTabInterval:[self ptsFromCMF:3.0]];
        [para setFirstLineHeadIndent:0];
        //[para setHeaderLevel:0];
        [para setHeadIndent:0.0];
        [para setHyphenationFactor:0.0];
        [para setLineBreakMode:NSLineBreakByWordWrapping];
        [para setLineHeightMultiple:1.0];
        [para setLineSpacing:0.0];
        [para setMaximumLineHeight:0];
        [para setMinimumLineHeight:0];
        [para setParagraphSpacing:6];
        [para setParagraphSpacingBefore:3];
        //[para setTabStops:<#(NSArray *)#>];
        [para setTailIndent:0.0];
        return para;
    }
-(NSNumber*)ptsFromCMN:(float)cm
{
    return [NSNumber numberWithFloat:[self ptsFromCMF:cm]];
}
-(float)ptsFromCMF:(float)cm
{
    return cm * 28.3464567;
}

感谢提供代码示例。我相信提取最小代码一定很有趣,但这比试图在TextKit API文档中寻找答案要好得多 :-) - Frank R.
尝试使用setFirstLineHeadIndent、setHeadIndent和setTabStops,你可能需要同时使用它们三个来创建正确缩进的项目符号段落。然而请注意,您正在设置段落样式,如果您不设置所有内容,则可能会得到一些奇怪的结果。 - Duncan Groenewald
@DuncanGroenewald 谢谢您!顺便说一句,我使用了一个非常简化的版本来制作编号列表。基本上,我设置了一个值为“X”(在我的情况下是20.0f)的 NSTextTab 并将我的 headIndent 设置为相同的值。然后,我的字符串是 @"1.\t{long text here}\n2.\t{more long text}"。它完美地对齐了所有内容,即使有换行也没问题。感谢您! - mbm29414
如果你正在寻找提取的最小代码,请查看我的回答:https://dev59.com/BGIk5IYBdhLWcg3wG6w6#26715297。 - Lukas Petr

8

我找到的最简单的解决方案如下:

let bulletList = UILabel()
let bulletListArray = ["line 1 - enter a bunch of lorem ipsum here so it wraps to the next line", "line 2", "line 3"]
let joiner = "\n"

var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.headIndent = 10
paragraphStyle.firstLineHeadIndent = 0

let attributes = [NSParagraphStyleAttributeName: paragraphStyle]
let bulletListString = joiner.join(bulletListArray.map { "• \($0)" })

bulletList.attributedText = NSAttributedString(string: bulletListString, attributes: attributes)

这个理论是数组中的每个字符串都像一个“段落”,而段落样式在第一行上得到0缩进,使用map方法添加了一个符号。然后对于之后的每一行,它都会得到10像素的缩进(根据您的字体度量调整间距)。


6

其他答案仅仅是通过设置一个常量值来确定缩进大小。这意味着,如果你更改字体,就必须手动更新它,并且如果使用了动态类型,则效果不佳。幸运的是,测量文本很容易。

假设你有一些文本和一些属性:

NSString *text = @"• Some bulleted paragraph";
UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
NSDictionary *attributes = @{NSFontAttributeName: font};

以下是如何测量文本并据此创建段落样式的步骤:

这里有一个示例:

NSString *bulletPrefix = @"• ";
CGSize size = [bulletPrefix sizeWithAttributes:attributes];
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.headIndent = size.width;

我们将此插入到我们的属性中并创建属性字符串:
NSMutableDictionary *indentedAttributes = [attributes mutableCopy];
indentedAttributes[NSParagraphStyleAttributeName] = [paragraphStyle copy];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text attributes:indentedAttributes];

5

Swift 5

我为NSAttributedString 创建了一个扩展,添加了方便的初始化程序,可以正确缩进不同类型的列表。

extension NSAttributedString {

    convenience init(listString string: String, withFont font: UIFont) {
        self.init(attributedListString: NSAttributedString(string: string), withFont: font)
    }

    convenience init(attributedListString attributedString: NSAttributedString, withFont font: UIFont) {
        guard let regex = try? NSRegularExpression(pattern: "^(\\d+\\.|[•\\-\\*])(\\s+).+$",
                                                   options: [.anchorsMatchLines]) else { fatalError() }
        let matches = regex.matches(in: attributedString.string, options: [],
                                    range: NSRange(location: 0, length: attributedString.string.utf16.count))
        let nsString = attributedString.string as NSString
        let mutableAttributedString = NSMutableAttributedString(attributedString: attributedString)

        for match in matches {
            let size = NSAttributedString(
                string: nsString.substring(with: match.range(at: 1)) + nsString.substring(with: match.range(at: 2)),
                attributes: [.font: font]).size()
            let indentation = ceil(size.width)
            let range = match.range(at: 0)

            let paragraphStyle = NSMutableParagraphStyle()

            if let style = attributedString.attribute(.paragraphStyle, at: 0, longestEffectiveRange: nil, in: range)
                as? NSParagraphStyle {
                paragraphStyle.setParagraphStyle(style)
            }

            paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: indentation, options: [:])]
            paragraphStyle.defaultTabInterval = indentation
            paragraphStyle.firstLineHeadIndent = 0
            paragraphStyle.headIndent = indentation

            mutableAttributedString.addAttribute(.font, value: font, range: range)
            mutableAttributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: range)
        }

        self.init(attributedString: mutableAttributedString)
    }
}

示例用法: 方便的初始化器使用方式

每个符号后面的空格数量并不重要。代码将根据您决定在项目符号后面有多少制表符或空格来动态计算适当的缩进宽度。

如果属性字符串已经具有段落样式,该便利初始化器将保留该段落样式的选项并应用自己的一些选项。

支持的符号: •、-、*、数字后跟句点(例如 8.)


2
您可以使用“属性检查器”执行此简单操作,选择缩进字段并进行所需更改即可 :) enter image description here

1

基于thisispete的解决方案,更新为Swift 4.2。

Swift 4.2

let array = ["1st", "2nd", "3rd"]
let textView = UITextView()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 0
paragraphStyle.headIndent = 12
let bulletListText = array.map { "• \($0)" }.joined(separator: "\n")
let attributes = [
    NSAttributedString.Key.paragraphStyle: paragraphStyle,
    NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17.0)
]
textView.attributedText = NSAttributedString(string: bulletListText, attributes: attributes)

0

我基于Lukas的实现,做了一个快速解决方案(目前是Swift 2.3版本)。在没有项目符号的行上遇到了一点问题,所以我创建了一个扩展,这样你就可以选择性地传递一个范围来应用段落样式。

extension String{

    func getAllignedBulletPointsMutableString(bulletPointsRange: NSRange = NSMakeRange(0, 0)) -> NSMutableAttributedString{

        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.paragraphSpacing = 0
        paragraphStyle.paragraphSpacingBefore = 0
        paragraphStyle.firstLineHeadIndent = 0
        paragraphStyle.headIndent = 7.5

        attributedString.addAttributes([NSParagraphStyleAttributeName: paragraphStyle], range: bulletPointsRange)
        return attributedString
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接