使用项目符号格式化 UILabel?

发布于 2024-10-29 16:15:40 字数 100 浏览 1 评论 0原文

是否可以格式化 UILabel 中的文本以显示项目符号点

如果是这样,我该怎么办?

Is it possible to format the text in a UILabel to show a bullet point?

If so, How can I do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

臻嫒无言 2024-11-05 16:15:41

是的。复制并粘贴以下项目符号: 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

Yes. Copy and paste the following bullet: Swift's compiler can interpret and display the bullet as desired within Xcode, nothing else needed.

Reuse

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


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

output

• Buy apples
• Buy oranges

Reusable array

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)

output

• get apples
• get oranges
• get a bannana
音盲 2024-11-05 16:15:41

查看此链接,我制作了一个自定义视图,以使用项目符号/其他符号/图像(使用 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

         } 
    }

Check out this link, I made a Custom view to format text with bullet points/ other symbols/ image(using attributeText property of UILabel) as list item symbol (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

         } 
    }
无法回应 2024-11-05 16:15:41

如果您还想对齐项目符号点的文本缩进,则可以使用以下方法来构建具有适当缩进和间距属性的 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];

If you want to align the text indenting for the bullet points as well, you can use the following method that builds a NSAttributedString with the proper indentation and spacing properties:

- (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;
}

And you can use that method as follows, by passing an NSArray with the texts and providing you already have a 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];
挥剑断情 2024-11-05 16:15:41

以下是 @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
    }
}

Here's the solution from @krunal refactored into Swift 5 NSAttributedString extension:

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
    }
}
殤城〤 2024-11-05 16:15:41

对我来说,解决方案是在 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 *****")

The solution for me is using a extension on 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)
}

And call it:

var bullet = "* "
self.label.setBulletAttributes(bullet:bullet, text: bullet + "Test *****")
憧憬巴黎街头的黎明 2024-11-05 16:15:41

如果有人像我一样寻找带有项目符号点的文本视图文本,下面就是答案。顺便说一句,它仅适用于静态文本。

•   Better experience - Refer a friend and How to Play \n• Tournaments performance improvement\n• UI/UX Improvements\n• Critical bug fixes

我已将上面的文本分配给textview。它按我的预期工作。

If anyone looking for textview text with bullet points like me, below is the answer. By the way it works only for static text.

•   Better experience - Refer a friend and How to Play \n• Tournaments performance improvement\n• UI/UX Improvements\n• Critical bug fixes

I have assigned above text to textview. It worked as intended for me.

心如荒岛 2024-11-05 16:15:41

在这里,我添加了一个带有要点的警报视图控制器,希望这会有所帮助。

*** 笔记:
这仅适用于 UIAlertViewController

  func showBulletPointsAlert(title:String,subTitles:[String],getCompleted: @escaping((_ selected: Int) -> ())) {
        let alertController = UIAlertController(title: "\(title)\n", message: nil, preferredStyle: .alert)
        let value = convertToList(subTitles: subTitles, font: .boldSystemFont(ofSize: 14))
        alertController.setValue(value, forKey: "attributedMessage")

        let okAction = UIAlertAction(title: "Continue", style: .default, handler: { _ in
            getCompleted(0)
        })
        alertController.addAction(okAction)

        if let rootViewController = UIApplication.shared.windows.first?.rootViewController {
            rootViewController.present(alertController, animated: true, completion: nil)
        }
    }
    
    func convertToList(subTitles: [String],
             font: UIFont,
             bullet: String = "\u{2022}",
             indentation: CGFloat = 20,
             lineSpacing: CGFloat = 2,
             paragraphSpacing: CGFloat = 12,
             textColor: UIColor = .gray,
                       bulletColor: UIColor = ThemeManager.shared.mainTextColor) -> 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.lineSpacing = lineSpacing
        paragraphStyle.paragraphSpacing = paragraphSpacing
        paragraphStyle.headIndent = indentation
        paragraphStyle.lineBreakMode = .byCharWrapping

        let bulletList = NSMutableAttributedString()
        for titles in subTitles {
            let formattedString = "\(bullet)\t\(titles)\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
    }
   

Here I have added an alert view controller with bullet points, Hope this helps.

*** Note:
This is for only UIAlertViewController

  func showBulletPointsAlert(title:String,subTitles:[String],getCompleted: @escaping((_ selected: Int) -> ())) {
        let alertController = UIAlertController(title: "\(title)\n", message: nil, preferredStyle: .alert)
        let value = convertToList(subTitles: subTitles, font: .boldSystemFont(ofSize: 14))
        alertController.setValue(value, forKey: "attributedMessage")

        let okAction = UIAlertAction(title: "Continue", style: .default, handler: { _ in
            getCompleted(0)
        })
        alertController.addAction(okAction)

        if let rootViewController = UIApplication.shared.windows.first?.rootViewController {
            rootViewController.present(alertController, animated: true, completion: nil)
        }
    }
    
    func convertToList(subTitles: [String],
             font: UIFont,
             bullet: String = "\u{2022}",
             indentation: CGFloat = 20,
             lineSpacing: CGFloat = 2,
             paragraphSpacing: CGFloat = 12,
             textColor: UIColor = .gray,
                       bulletColor: UIColor = ThemeManager.shared.mainTextColor) -> 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.lineSpacing = lineSpacing
        paragraphStyle.paragraphSpacing = paragraphSpacing
        paragraphStyle.headIndent = indentation
        paragraphStyle.lineBreakMode = .byCharWrapping

        let bulletList = NSMutableAttributedString()
        for titles in subTitles {
            let formattedString = "\(bullet)\t\(titles)\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
    }
   
时光礼记 2024-11-05 16:15:40

也许对字符串中的项目符号字符使用 Unicode 代码点?

Objective-c

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

Swift 4

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

Perhaps use the Unicode code point for the bullet character in your string?

Objective-c

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

Swift 4

myLabel.text = "\u{2022} This is a list item!"
夏尔 2024-11-05 16:15:40

只需添加 " • "

即使我也在为我的 textView 寻找类似的东西。我所做的,只需将我的字符串附加到上面的字符串并将其传递给我的 textView,也可以对 labels 执行相同的操作。

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

just add " • "

Even i was looking for something like this for my textView. What i did, just append above string with my string and pass it to my textView, same can be done for labels also.

I answered this for future Viewer.

霊感 2024-11-05 16:15:40

这是使用 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 nice solution with 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)

Add bullet attributes

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:

enter image description here

灼疼热情 2024-11-05 16:15:40

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"
  }

输出:

在此处输入图像描述

In Swift 4 i have used " • " with new Line

 @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"
  }

Output:

enter image description here

你列表最软的妹 2024-11-05 16:15:40

在斯威夫特 3.1 中

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

In swift 3.1

lblItemName.text = "\u{2022} This is a list item!"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文