iOS7 TextKit:项目符号对齐

Fra*_* R. 19 cocoa-touch uitextview ios ios7 textkit

我正在为iOS 7编写一个应用程序,我正在尝试在不可编辑的UITextView中获得不错的格式.

插入一个子弹点角色很容易,但当然左压痕不会跟随.iOS 7在弹出点后设置左缩进的最简单方法是什么?

提前致谢,

坦率

Luk*_*etr 45

所以我环顾四周,这里是Duncan的答案提取的最小代码,以使其工作:

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;
Run Code Online (Sandbox Code Playgroud)

这是我的应用程序中的结果:

二次大师


Dun*_*ald 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;
}
Run Code Online (Sandbox Code Playgroud)


thi*_*ete 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)
Run Code Online (Sandbox Code Playgroud)

理论是数组中的每个字符串就像一个'段落',段落样式在第一行得到0缩进,它使用map方法获得一个子弹..然后为每一行获得10 px缩进(调整间距)为您的字体指标)


ska*_*dal 6

其他答案依赖于使用常量值设置缩进大小.这意味着如果您要更改字体,则必须手动更新它,如果您使用的是动态类型,则无法正常工作.幸运的是,测量文本很容易.

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

NSString *text = @"• Some bulleted paragraph";
UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
NSDictionary *attributes = @{NSFontAttributeName: font};
Run Code Online (Sandbox Code Playgroud)

以下是如何测量项目符号并相应地创建段落样式:

NSString *bulletPrefix = @"• ";
CGSize size = [bulletPrefix sizeWithAttributes:attributes];
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.headIndent = size.width;
Run Code Online (Sandbox Code Playgroud)

我们在属性中插入它并创建属性字符串:

NSMutableDictionary *indentedAttributes = [attributes mutableCopy];
indentedAttributes[NSParagraphStyleAttributeName] = [paragraphStyle copy];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text attributes:indentedAttributes];
Run Code Online (Sandbox Code Playgroud)


Ton*_*čić 5

斯威夫特 4

我为此做了一个扩展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)
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例: 如何使用便利初始化程序

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

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

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