如何使用圆点符号格式化UILabel?

108

是否有可能在 UILabel 中格式化 text 以显示圆点符号

如果可以,我该怎么做?


@Hoque:UILabel不会将其文本视为HTML。 - Ben Zotto
2
这里有一个相关的类!https://codeload.github.com/eyalc/ECListView/zip/master - Hemang
22
为什么这个问题被关闭了?这是一个合法的问题,有一个合法的答案。 - len
2
为什么http://stackoverflow.com/users/237838/andrew-barber将这个标记为离题,它可能是一个重复的问题,但绝不是离题的... - AppHandwerker
3
快捷键 ALT+8 = • - TheTiger
可能是一个重复问题:NSAttributedString插入项目符号? - Jonathan Cabrera
12个回答

190

也许你可以在字符串中使用 Unicode 码点来表示项目符号字符?

Objective-C

myLabel.text = @"\u2022 This is a list item!";

Swift 4

myLabel.text = "\u{2022} This is a list item!"

4
请原谅我的无知,但我一直在使用UILabels,不知道您能否举个“例子”。 - daveMac
1
myLabel.numberOfLines = 0 可以让标签支持多行,并且会保留换行符。总的来说,我更喜欢使用 UITextField,因为它更加灵活。例如,在使用 UITextField 时,您可以轻松检测到用户点击了哪个字符,而我认为您不能使用 UILabel 实现这一点。文本视图还具有许多其他有用的功能。 - John Erck
7
另一种方法是使用 option+8 - atulkhatri
4
记得如果您使用本地化字符串,请使用大写的“U”:\U2022 - Nikolaj Simonsen
1
Swift 稍有不同,"\u{2022}" - anders
显示剩余5条评论

97

只需添加" • "

我也在寻找类似于这样的东西用于我的textView。 我所做的就是将上述字符串附加到我的字符串中,并将其传递给我的textView,对于labels也可以使用相同方法。

我为未来的观众解答了这个问题。


对我有用。我在Xcode中使用了*,我只是使用•进行复制/替换,对于我的标签来说它很好用,我用•替换了“Label”。 - Brian Bird

81

这里有一个使用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)

添加项目符号属性
func add(stringList: [String],
         font: UIFont,
         bullet: String = "\u{2022}",
         indentation: CGFloat = 20,
         lineSpacing: CGFloat = 2,
         paragraphSpacing: CGFloat = 12,
         textColor: UIColor = .gray,
         bulletColor: UIColor = .red) -> 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
}

这是结果:

图片描述


(注:原文中的“Here is result”已经被翻译成了“这是结果”。)

1
这是一个非常优雅的解决方案。 - Jeroen

11
在Swift 4中,我使用“•”来换行。
 @IBOutlet weak var bulletLabel: UILabel!
 let arrayOfLines = ["Eat egg for protein","You should Eat Ghee","Wheat is with high fiber","Avoid to eat Fish "]
 for value in arrayOfLines {
     bulletLabel.text = bulletLabel.text!  + " • " + value + "\n"
  }

输出:

输入图像描述


16
为什么要避免食用鱼? - rd_

8

在Swift 3.1中

lblItemName.text = "\u{2022} This is a list item!"

7

好的。请复制并粘贴以下符号: Swift编译器可以在Xcode中按照需要解释和显示该符号,无需其他操作。

重用

extension String {
    static var bullet: String {
        return "• "
    }
}


print(String.bullet + "Buy apples")
let secondPoint: String = .bullet + "Buy oranges"
print(secondPoint)

输出

• Buy apples
• Buy oranges

可重复使用的数组

extension Array where Element == String {

    var bulletList: String {
        var po = ""
        for (index, item) in self.enumerated() {
            if index != 0 {
                po += "\n"
            }
            po += .bullet + item
        }
        return po
    }
}


print(["get apples", "get oranges", "get a bannana"].bulletList)

输出

 get apples
 get oranges
 get a bannana

1
如果你要给负评,请至少礼貌地说明原因。 - ScottyBlades
我认为原因是因为你的解决方案不够优化。使用Unicode代码点是最佳选择。 - Robert J. Clegg
感谢您周到的回复。为什么Unicode点更好? - ScottyBlades
因为如果开发人员需要在不同的屏幕或项目中多次执行此操作(不是在同一时间段内),了解代码点值将对他们更有益。因此,他们不需要去查找上面的答案或类似的地方来复制它。这就是我的想法。 - Robert J. Clegg
1
@RobertJ.Clegg 我刚刚更新了我的答案,提供了一个可重复使用的选项。你能给我举个例子,说明何时使用代码点字符串比直接使用项目符号字符串更具可重用性吗? - ScottyBlades

4

如果你想对项目符号的文本缩进进行对齐,你可以使用以下方法,该方法构建了一个具有适当缩进和间距属性的NSAttributedString

- (NSAttributedString *)attributedStringForBulletTexts:(NSArray *)stringList
                                              withFont:(UIFont *)font
                                          bulletString:(NSString *)bullet
                                           indentation:(CGFloat)indentation
                                           lineSpacing:(CGFloat)lineSpacing
                                      paragraphSpacing:(CGFloat)paragraphSpacing
                                             textColor:(UIColor *)textColor
                                           bulletColor:(UIColor *)bulletColor {

    NSDictionary *textAttributes = @{NSFontAttributeName: font,
                                 NSForegroundColorAttributeName: textColor};
    NSDictionary *bulletAttributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: bulletColor};

    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.tabStops = @[[[NSTextTab alloc] initWithTextAlignment: NSTextAlignmentLeft location:indentation options:@{}]];
    paragraphStyle.defaultTabInterval = indentation;
    paragraphStyle.lineSpacing = lineSpacing;
    paragraphStyle.paragraphSpacing = paragraphSpacing;
    paragraphStyle.headIndent = indentation;

    NSMutableAttributedString *bulletList = [NSMutableAttributedString new];

    for (NSString *string in stringList) {
        NSString *formattedString = [NSString stringWithFormat:@"%@\t%@\n", bullet, string];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:formattedString];
        if (string == stringList.lastObject) {
            paragraphStyle = [paragraphStyle mutableCopy];
            paragraphStyle.paragraphSpacing = 0;
        }
        [attributedString addAttributes:@{NSParagraphStyleAttributeName: paragraphStyle} range:NSMakeRange(0, attributedString.length)];
        [attributedString addAttributes:textAttributes range:NSMakeRange(0, attributedString.length)];

        NSRange rangeForBullet = [formattedString rangeOfString:bullet];
        [attributedString addAttributes:bulletAttributes range:rangeForBullet];
        [bulletList appendAttributedString:attributedString];
    }

    return bulletList;
}

您可以按照以下方式使用该方法,通过传递一个包含文本的 NSArray 并提供已经有一个 UILabel

NSArray *stringArray = @[@"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 = [self attributedStringForBulletTexts:stringArray
                                                   withFont:label.font
                                               bulletString:@"•"
                                                indentation:15
                                                lineSpacing:2
                                           paragraphSpacing:10
                                                  textColor:UIColor.blackColor
                                                bulletColor:UIColor.grayColor];

这段代码有一个小问题,它会在结尾处添加一个额外的换行符。因此,您需要添加一个条件语句,如果是最后一行,则不要添加换行符。例如:NSString *lineWrap = string == stringList.lastObject ? @"" : @"\n"; NSString *formattedString = [NSString stringWithFormat:@"%@\t%@%@", bullet, string, lineWrap]; - Vincent Sit

3

请查看此链接,我制作了一个自定义视图,以符号(使用UILabel的attributeText属性)格式化文本为列表项符号(Swift 3.0)。 https://github.com/akshaykumarboth/SymbolTextLabel-iOS-Swift

 import UIKit

    class ViewController: UIViewController {

    @IBOutlet var symbolView: SymbolTextLabel!

    var testString = "Understanding the concept of sales"

    var bulletSymbol = "\u{2022}" 
    var fontsize: CGFloat= 18
    override func viewDidLoad() {

        super.viewDidLoad()
         //First way // Dynamically creating SymbolTextLabel object

        let symbolTextLabel = SymbolTextLabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))

        symbolTextLabel.setText(text: testString, symbolCode: bulletSymbol) //setting text and symbol of text item

        symbolTextLabel.setFontSize(textSize: fontsize) // setting font size

        //symbolTextLabel.setSpacing(spacing: 5) // setting space between symbol and text

        self.view.addSubview(symbolTextLabel) 
//second way // from storyboard or interface builder

     symbolView.setText(text: testString, symbolCode: bulletSymbol)
 //setting text and symbol of text item 

    symbolView.setFontSize(textSize: fontsize) // setting font size

        //symbolView.setSpacing(spacing: 5) // setting space between symbol and text

         } 
    }

2
这是来自@krunal的解决方案,在Swift 5中进行了重构,使用NSAttributedString扩展:
import UIKit

public extension NSAttributedString {
    static func makeBulletList(from strings: [String],
                               bulletCharacter: String = "\u{2022}",
                               bulletAttributes: [NSAttributedString.Key: Any] = [:],
                               textAttributes: [NSAttributedString.Key: Any] = [:],
                               indentation: CGFloat = 20,
                               lineSpacing: CGFloat = 1,
                               paragraphSpacing: CGFloat = 10) -> NSAttributedString
    {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.defaultTabInterval = indentation
        paragraphStyle.tabStops = [
            NSTextTab(textAlignment: .left, location: indentation)
        ]
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.paragraphSpacing = paragraphSpacing
        paragraphStyle.headIndent = indentation

        let bulletList = NSMutableAttributedString()

        for string in strings {
            let bulletItem = "\(bulletCharacter)\t\(string)\n"

            var attributes = textAttributes
            attributes[.paragraphStyle] = paragraphStyle

            let attributedString = NSMutableAttributedString(
                string: bulletItem, attributes: attributes
            )

            if !bulletAttributes.isEmpty {
                let bulletRange = (bulletItem as NSString).range(of: bulletCharacter)
                attributedString.addAttributes(bulletAttributes, range: bulletRange)
            }

            bulletList.append(attributedString)
        }

        if bulletList.string.hasSuffix("\n") {
            bulletList.deleteCharacters(
                in: NSRange(location: bulletList.length - 1, length: 1)
            )
        }

        return bulletList
    }
}

0
我的解决方案是在uilabel上使用扩展。
extension UILabel{
func setBulletAttributes(bullet:String , text:String){
    var attributes = [NSAttributedString.Key: Any]()
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.headIndent = (bullet as NSString).size(withAttributes: attributes).width
    attributes[.paragraphStyle] = paragraphStyle
    self.attributedText = NSAttributedString(string: text, attributes: attributes)
}

然后调用它:

var bullet = "* "
self.label.setBulletAttributes(bullet:bullet, text: bullet + "Test *****")

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