美文网首页
iOS 字体换行 为什么出现左右不齐,如何才能保持左右对齐?

iOS 字体换行 为什么出现左右不齐,如何才能保持左右对齐?

作者: writeSpace | 来源:发表于2023-04-18 15:08 被阅读0次

    iOS 字体换行出现左右不齐的原因可能是由于不同的字体在不同的字符串长度下,字符的占用宽度是不同的,导致部分行的文字长度不一致,从而产生了左右不齐的情况。解决这个问题的方法有以下两种:

    通过属性字符串(NSAttributedString)设置固定宽度

    通过设置属性字符串的固定宽度,可以使文字在该宽度内居中对齐,即使文字长度不同,也不会出现左右不齐的现象。下面是一个示例代码:

    let text = "要显示的文字"
    let font = UIFont.systemFont(ofSize: 20)
    let maxWidth: CGFloat = 200
    
    let attributedString = NSMutableAttributedString(string: text)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .byWordWrapping
    paragraphStyle.alignment = .center
    
    let range = NSRange(location: 0, length: text.count)
    attributedString.addAttribute(.font, value: font, range: range)
    attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: range)
    
    let boundingRect = attributedString.boundingRect(with: CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
    let height = ceil(boundingRect.height)
    
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: maxWidth, height: height))
    label.numberOfLines = 0
    label.attributedText = attributedString
    
    

    在上面的代码中,我们使用了NSMutableParagraphStyle设置了居中对齐模式,然后通过CGSize的最大宽度设置了一个固定的UILabel的宽度,最后通过boundingRect计算出了字符串的高度和UILabel的高度,将UILabel的高度设置为字符串高度,从而保证了左右对齐。

    将所有字符串补齐至最长字符串长度

    如果有多行文字需要对齐,可以先找到长度最长的字符串,然后将所有短字符串补齐至最长字符串长度,再统一使用固定宽度或其他方式进行对齐。

    let text = "要显示的文字"
    let font = UIFont.systemFont(ofSize: 20)
    let maxWidth: CGFloat = 200
    
    let attributedString = NSMutableAttributedString(string: text)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .byWordWrapping
    paragraphStyle.alignment = .center
    
    let range = NSRange(location: 0, length: text.count)
    attributedString.addAttribute(.font, value: font, range: range)
    attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: range)
    
    let boundingRect = attributedString.boundingRect(with: CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
    let height = ceil(boundingRect.height)
    
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: maxWidth, height: height))
    label.numberOfLines = 0
    label.attributedText = attributedString
    
    
    

    相关文章

      网友评论

          本文标题:iOS 字体换行 为什么出现左右不齐,如何才能保持左右对齐?

          本文链接:https://www.haomeiwen.com/subject/vvghjdtx.html