NSAttributedString插入一个项目符号点?

ary*_*axt 25 objective-c bulletedlist nsattributedstring ios swift

所以我有一个NSAttributedString我想bullet point在一部分文本的开头插入一个.我怎样才能做到这一点?如何CTPAragraphStyle在显示文本时创建创建此项目符号点?

编辑: 应该可以在iOS上使用

Obl*_*ely 34

简单的一点:[mutableAttributedString insertAttributedString:@"•\ t"atIndex:0];

硬位.以下几行.(这是从一个更大的项目中提取的,但它可能会给你一个不错的开始.)

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"•\texample bullet fill out the text to check what happens on the second line and make sure it is lining up OK"];

CTTextAlignment alignment = kCTLeftTextAlignment;
CGFloat paragraphSpacing = 0.0;
CGFloat paragraphSpacingBefore = 0.0;
CGFloat firstLineHeadIndent = 15.0;
CGFloat headIndent = 30.0;

CGFloat firstTabStop = 15.0; // width of your indent
CGFloat lineSpacing = 0.45;

CTTextTabRef tabArray[] = { CTTextTabCreate(0, firstTabStop, NULL) };

CFArrayRef tabStops = CFArrayCreate( kCFAllocatorDefault, (const void**) tabArray, 1, &kCFTypeArrayCallBacks );
CFRelease(tabArray[0]);

CTParagraphStyleSetting altSettings[] = 
{
    { kCTParagraphStyleSpecifierLineSpacing, sizeof(CGFloat), &lineSpacing},
    { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &alignment},
    { kCTParagraphStyleSpecifierFirstLineHeadIndent, sizeof(CGFloat), &firstLineHeadIndent},
    { kCTParagraphStyleSpecifierHeadIndent, sizeof(CGFloat), &headIndent},
    { kCTParagraphStyleSpecifierTabStops, sizeof(CFArrayRef), &tabStops},
    { kCTParagraphStyleSpecifierParagraphSpacing, sizeof(CGFloat), &paragraphSpacing},
    { kCTParagraphStyleSpecifierParagraphSpacingBefore, sizeof(CGFloat), &paragraphSpacingBefore}
}; 

CTParagraphStyleRef style;
style = CTParagraphStyleCreate( altSettings, sizeof(altSettings) / sizeof(CTParagraphStyleSetting) );

if ( style == NULL )
{
    NSLog(@"*** Unable To Create CTParagraphStyle in apply paragraph formatting" );
    return;
}

[string addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:(NSObject*)style,(NSString*) kCTParagraphStyleAttributeName, nil] range:NSMakeRange(0,[string length])];

CFRelease(tabStops);
CFRelease(style);
Run Code Online (Sandbox Code Playgroud)

您需要包含CoreText框架,然后导入CoreText/CoreText.h


小智 33

这是一个更现代的方法,适用于iOS6:

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"•\texample bullet fill out the text to check what happens on the second line and make sure it is lining up OK"];

NSMutableParagraphStyle *paragraphStyle;
paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setTabStops:@[[[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft location:15 options:nil]]];
[paragraphStyle setDefaultTabInterval:15];
[paragraphStyle setFirstLineHeadIndent:0];
[paragraphStyle setHeadIndent:15];

[string addAttributes:@{NSParagraphStyleAttributeName: paragraphStyle} range:NSMakeRange(0,[string length])];
Run Code Online (Sandbox Code Playgroud)


Kru*_*nal 20

这是Swift很好的解决方案

let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 600)
label.textColor = UIColor.lightGray
label.numberOfLines = 0

let arrayString = [
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
    "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
    "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
]

label.attributedText = add(stringList: arrayString, font: label.font, bullet: "?")

self.view.addSubview(label)
Run Code Online (Sandbox Code Playgroud)

添加项目符号

Swift 4.2 ++

func add(stringList: [String],
         font: UIFont,
         bullet: String = "\u{2022}",
         indentation: CGFloat = 20,
         lineSpacing: CGFloat = 2,
         paragraphSpacing: CGFloat = 12,
         textColor: UIColor = .gray,
         bulletColor: UIColor = .green) -> NSAttributedString {

    let textAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: textColor]
    let bulletAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: bulletColor]

    let paragraphStyle = NSMutableParagraphStyle()
    let nonOptions = [NSTextTab.OptionKey: Any]()
    paragraphStyle.tabStops = [
        NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
    paragraphStyle.defaultTabInterval = indentation
    //paragraphStyle.firstLineHeadIndent = 0
    //paragraphStyle.headIndent = 20
    //paragraphStyle.tailIndent = 1
    paragraphStyle.lineSpacing = lineSpacing
    paragraphStyle.paragraphSpacing = paragraphSpacing
    paragraphStyle.headIndent = indentation

    let bulletList = NSMutableAttributedString()
    for string in stringList {
        let formattedString = "\(bullet)\t\(string)\n"
        let attributedString = NSMutableAttributedString(string: formattedString)

        attributedString.addAttributes(
            [NSAttributedString.Key.paragraphStyle : paragraphStyle],
            range: NSMakeRange(0, attributedString.length))

        attributedString.addAttributes(
            textAttributes,
            range: NSMakeRange(0, attributedString.length))

        let string:NSString = NSString(string: formattedString)
        let rangeForBullet:NSRange = string.range(of: bullet)
        attributedString.addAttributes(bulletAttributes, range: rangeForBullet)
        bulletList.append(attributedString)
    }

    return bulletList
}
Run Code Online (Sandbox Code Playgroud)

Swift 4.0和4.1

func add(stringList: [String],
         font: UIFont,
         bullet: String = "\u{2022}",
         indentation: CGFloat = 20,
         lineSpacing: CGFloat = 2,
         paragraphSpacing: CGFloat = 12,
         textColor: UIColor = .gray,
         bulletColor: UIColor = .green) -> NSAttributedString {

    let textAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor]
    let bulletAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: bulletColor]

    let paragraphStyle = NSMutableParagraphStyle()
    let nonOptions = [NSTextTab.OptionKey: Any]()
    paragraphStyle.tabStops = [
        NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
    paragraphStyle.defaultTabInterval = indentation
    //paragraphStyle.firstLineHeadIndent = 0
    //paragraphStyle.headIndent = 20
    //paragraphStyle.tailIndent = 1
    paragraphStyle.lineSpacing = lineSpacing
    paragraphStyle.paragraphSpacing = paragraphSpacing
    paragraphStyle.headIndent = indentation

    let bulletList = NSMutableAttributedString()
    for string in stringList {
        let formattedString = "\(bullet)\t\(string)\n"
        let attributedString = NSMutableAttributedString(string: formattedString)

        attributedString.addAttributes(
            [NSAttributedStringKey.paragraphStyle : paragraphStyle],
            range: NSMakeRange(0, attributedString.length))

        attributedString.addAttributes(
            textAttributes,
            range: NSMakeRange(0, attributedString.length))

        let string:NSString = NSString(string: formattedString)
        let rangeForBullet:NSRange = string.range(of: bullet)
        attributedString.addAttributes(bulletAttributes, range: rangeForBullet)
        bulletList.append(attributedString)
    }

    return bulletList
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述


Rob*_*ier 5

您没有在iOS中实现带有段落样式的项目符号列表.根据需要设置制表位,然后在段落的开头插入制表符,项目符号,制表符.

CTParagraphStyle是非常不灵活的,所以你不能只是添加你选择的新风格.但是,您可以将任何您喜欢的属性(MYBulletStyle)添加到其中的任意运行中NSAttributedString.这对于传递子弹列表信息非常有用NSAttributedString,然后在您准备好显示它时重建字符串以包含子弹.但Core Text不会自动为您渲染项目符号.


Jon*_*era 5

这是 Krunal 在Objective-C中的出色答案。它还删除了最后一个项目符号项上的段落间距,以避免 UILabel 上出现额外的底部填充。

\n\n
UILabel *label = [UILabel new];\nlabel.frame = CGRectMake(40, 100, 280, 600);\nlabel.textColor = UIColor.lightGrayColor;\nlabel.numberOfLines = 0;\n\nNSArray *stringArray = @[@"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",\n                         @"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",\n                         @"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",\n                         @"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."\n                         ];\n\nlabel.attributedText = [self attributedStringForBulletTexts:stringArray\n                                                   withFont:label.font\n                                               bulletString:@"\xef\xa3\xbf"\n                                                indentation:20\n                                                lineSpacing:2\n                                           paragraphSpacing:12\n                                                  textColor:UIColor.grayColor\n                                                bulletColor:UIColor.greenColor];\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是创建实际属性文本的函数:

\n\n
- (NSAttributedString *)attributedStringForBulletTexts:(NSArray *)stringList\n                                              withFont:(UIFont *)font\n                                          bulletString:(NSString *)bullet\n                                           indentation:(CGFloat)indentation\n                                           lineSpacing:(CGFloat)lineSpacing\n                                      paragraphSpacing:(CGFloat)paragraphSpacing\n                                             textColor:(UIColor *)textColor\n                                           bulletColor:(UIColor *)bulletColor {\n\n    NSDictionary *textAttributes = @{NSFontAttributeName: font,\n                                 NSForegroundColorAttributeName: textColor};\n    NSDictionary *bulletAttributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: bulletColor};\n\n    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];\n    paragraphStyle.tabStops = @[[[NSTextTab alloc] initWithTextAlignment: NSTextAlignmentLeft location:indentation options:@{}]];\n    paragraphStyle.defaultTabInterval = indentation;\n    paragraphStyle.lineSpacing = lineSpacing;\n    paragraphStyle.paragraphSpacing = paragraphSpacing;\n    paragraphStyle.headIndent = indentation;\n\n    NSMutableAttributedString *bulletList = [NSMutableAttributedString new];\n\n    for (NSString *string in stringList) {\n        NSString *formattedString = [NSString stringWithFormat:@"%@\\t%@\\n", bullet, string];\n        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:formattedString];\n        if ([string isEqualToString: stringList.lastObject]) {\n            paragraphStyle = [paragraphStyle mutableCopy];\n            paragraphStyle.paragraphSpacing = 0;\n        }\n        [attributedString addAttributes:@{NSParagraphStyleAttributeName: paragraphStyle} range:NSMakeRange(0, attributedString.length)];\n        [attributedString addAttributes:textAttributes range:NSMakeRange(0, attributedString.length)];\n\n        NSRange rangeForBullet = [formattedString rangeOfString:bullet];\n        [attributedString addAttributes:bulletAttributes range:rangeForBullet];\n        [bulletList appendAttributedString:attributedString];\n    }\n\n    return bulletList;\n}\n
Run Code Online (Sandbox Code Playgroud)\n