简体   繁体   中英

NSAttributedString: how to make multiline in another NSAttributedString

I am trying to create a multiline separate text in another text to achieve the below text style.

在此处输入图片说明

I have tried the below code to produce the goal but the third part of the code is creating a issue (with medium font)

在此处输入图片说明

    private func createLimitedDetailText() -> NSAttributedString {
        let totalText = "Attension, only\n 6 spaces\n left!"
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center

        let attributedString = NSMutableAttributedString(string: totalText, attributes: [
            .font: FontFamily.OpenSans.light.font(size: 29.0),
            .foregroundColor: UIColor.white,
            ])

        let bigText = attributedString.addAttribute(.font, value: FontFamily.OpenSans.extrabold.font(size: 70), range: NSRange(location: 17, length: 1))
        let medium = attributedString.addAttribute(.font, value: FontFamily.OpenSans.semibold.font(size: 29), range: NSRange(location: 18, length: 14))

        let textRange = NSRange(location: 0, length: attributedString.length)
        attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: textRange)

        return attributedString
    }

In case anyone is wondering the answer, below code generates the exact same result:

    private func createLimitedDetailText() -> NSAttributedString {
        let totalText = "Attension, only\n 6"
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineHeightMultiple = 0.90
        paragraphStyle.alignment = .center

        let attributedString = NSMutableAttributedString(string: totalText, attributes: [
            .font: FontFamily.OpenSans.light.font(size: 29.0),
            .foregroundColor: UIColor.white,
            NSAttributedString.Key.paragraphStyle: paragraphStyle
            ])

        attributedString.addAttribute(.font, value: FontFamily.OpenSans.extrabold.font(size: 70), range: NSRange(location: 17, length: 1))

        let paragraphStyle2 = NSMutableParagraphStyle()
        paragraphStyle2.lineHeightMultiple = 0.30
        paragraphStyle2.alignment = .center

        let attributedString2 = NSMutableAttributedString(string: "    spaces\n     left!", attributes: [
            .font: FontFamily.OpenSans.semibold.font(size: 29.0),
            .foregroundColor: UIColor.white,
            .baselineOffset: 35,
            .paragraphStyle: paragraphStyle2
            ])
        attributedString.append(attributedString2)

        return attributedString
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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