Search code examples
swiftdynamicsizecollectionview

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


I'm working with the collectionView whose each cell has the content like this: enter image description here

everything works pretty well until I test it on an iphone 5s:enter image description here

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


Solution

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