繁体   English   中英

如何快速对齐文本与 NSAttributedString

[英]How to Align Text with NSAttributedString in swift

我正在寻找NSAttributedString对齐文本。 它应该在相同的缩进(同一列上的字符串列表)。

输出:

在此处输入图片说明

我使用了下面的代码

    func setAttributedText() {
   
        let image1Attachment = NSTextAttachment()
        image1Attachment.image = UIImage(named: "checkgreen.png")
        image1Attachment.bounds = CGRect(x: 0,
                                         y: (contentLabel.font.capHeight - image1Attachment.image!.size.height).rounded() / 2, width: image1Attachment.image!.size.width,
                                         height: image1Attachment.image!.size.height)
        
        var attributes = [NSAttributedString.Key: Any]()
        attributes[.font] = UIFont.preferredFont(forTextStyle: .body)
        attributes[.foregroundColor] = UIColor.black
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.headIndent = 50
        attributes[.paragraphStyle] = paragraphStyle
        
        
        
        let line0 = NSAttributedString(string: "Dummy text is text that is used in the publishing industry or by web designers to occupy the space which will later be filled with 'real' content. \n")
        let line1 = NSAttributedString(string: "Your account will be charged for renewal within 24-hours prior to the end of the current subscription perio\n")
//        let line2 = NSAttributedString(string: "You can manage your subscriptions and turn off auto-renewal by going to your Account Settings on th")

            
        
        let checkgreenImageAttribute = NSMutableAttributedString(attributedString: NSAttributedString(attachment: image1Attachment))
        let finalString = NSMutableAttributedString(attributedString: checkgreenImageAttribute)
        finalString.append(line0)
        finalString.append(checkgreenImageAttribute)
        finalString.append(line1)
//        finalString.append(checkgreenImageAttribute)
//        finalString.append(line2)
        contentLabel.attributedText = finalString
    }

注意:我不想使用项目符号

在属性字符串中, NSTextAttachment成为字符串中的一个字符。

因此,在“组装”它后,将您的attributes应用于整个字符串:

    let checkgreenImageAttribute = NSMutableAttributedString(attributedString: NSAttributedString(attachment: image1Attachment))
    let finalString = NSMutableAttributedString(attributedString: checkgreenImageAttribute)
    finalString.append(line0)
    finalString.append(checkgreenImageAttribute)
    finalString.append(line1)
    
    // apply paragraph attributes here
    finalString.addAttributes(attributes, range: NSRange(location: 0, length: finalString.length))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM