简体   繁体   中英

Swift: Can I adjust attributed text with dynamic font size?

I'm working with the collectionView whose each cell has the content like this: 在此处输入图片说明

everything works pretty well until I test it on an iphone 5s: 在此处输入图片说明

"Ho Chi Minh City" was out of bounds. Here is my code:

func configureNameLabel() {
    nameLabel.numberOfLines = 2
    let attributedText = NSMutableAttributedString(string: post?.name ?? "", attributes: [.font: UIFont.boldSystemFont(ofSize: 15)])
    attributedText.append(NSAttributedString(string: "\nSaturday, December 1, 2018 ⦁ Ho Chi Minh City ⦁ ", attributes:
        [.foregroundColor: UIColor.lightGray, .font: UIFont.preferredFont(forTextStyle: .caption1)]))

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 5
    attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedText.string.count))

    let attachment = NSTextAttachment()
    attachment.image = UIImage(named: "user-male")
    attachment.bounds = CGRect(x: 0, y: -2, width: 12, height: 12)
    attributedText.append(NSAttributedString(attachment: attachment))

    nameLabel.attributedText = attributedText
}

I think this problem is due to the font size, can anybody fix this ?

Thanks guys, I solved it. "label.numberOfLines = 0" worked. the problem is at my constraints.

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