2016-12-24 72 views
0

我使用相同的字體在textView中獲得不同的行高爲什麼多行歸因String UITextView具有不同的行高?

如何設置固定行高?

我已經做了很多的嘗試,任何幫助表示讚賞,感謝

  • 集NSMutableParagraphStyle lineSpacing是沒用的
  • 集lineHeightMultiple是賺取差價更加明顯

[1]

demo

import UIKit 
import PlaygroundSupport 

let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 1000)) 
let data: [String] = [ 
    "商品名稱: 巧克力", 
    "商品名稱: 巧克力", 
    "商品名稱: 巧克力", 
    "註冊未成功,請驗證電子郵件", 
    "註冊未成功,請驗證電子郵件", 
    "註冊未成功,請驗證電子郵件", 
    "測試文字, 測試文字,測試文字", 
    "測試文字, 測試文字,測試文字", 
    "測試文字, 測試文字,測試文字", 
] 
let textView = UITextView(frame: view.frame) 


let paragraphStyle = NSMutableParagraphStyle() 
let bodyFont = UIFont.systemFont(ofSize: 20.0) 
paragraphStyle.lineHeightMultiple = 4 
var stripe = false 

// attributedString 
let mutableAttributedString = NSMutableAttributedString(string: "Test TextViewAttributedString\n", attributes: [ 
    NSFontAttributeName: UIFont.systemFont(ofSize: 18.0) 
    ]) 

for text: String in data { 
    var backgroundColor = UIColor(red:0.13, green:0.38, blue:0.95, alpha:1.00) 
    if stripe { 
     backgroundColor = UIColor(red:0.92, green:0.12, blue:0.38, alpha:1.00) 
    } 

    let contentAttributedString = NSAttributedString(string: text, attributes: [ 
     NSBackgroundColorAttributeName: backgroundColor, 
     NSParagraphStyleAttributeName: paragraphStyle, 
     NSFontAttributeName: bodyFont 
     ]) 
    mutableAttributedString.append(contentAttributedString) 
    stripe = !stripe 

    // add newline character 
    let newlineAttributedString = NSAttributedString(string: "\n") 
    mutableAttributedString.append(newlineAttributedString) 
} 

textView.attributedText = mutableAttributedString 
view.addSubview(textView) 


PlaygroundPage.current.liveView = view 

回答

0

我找到了原因,newlineAttributedString還需要NSFontAttributeName

let newlineAttributedString = NSAttributedString(string: "\n", attributes: [ 
    NSFontAttributeName: bodyFont 
]) 
mutableAttributedString.appendAttributedString(newlineAttributedString) 
相關問題