为什么wordWrapping结果不同CATextlayer和UILabel

时间:2017-06-25 23:24:58

标签: swift uilabel catextlayer

我正在尝试使用CATextLayer和UILabel设置文本。

相同的字体,大小和边界但WordWrapping结果不同。

UILabel Result

CATextLayer Result

这是我的代码。

 let textHeaderAttributes = [
            NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 24), // font
            NSAttributedStringKey.foregroundColor: UIColor.white,           // text color
//            NSAttributedStringKey.backgroundColor: UIColor.black
        ]



let textHeader = NSAttributedString(string: "A classic, meaningful, functional gift", attributes: textHeaderAttributes )

 //CATextLayer
    let frontHeaderText = CATextLayer()

  frontHeaderText.string = textHeader
        frontHeaderText.contentsScale = UIScreen.main.scale
        frontHeaderText.isWrapped = true
        frontHeaderText.alignmentMode = kCAAlignmentLeft
        frontHeaderText.frame = CGRect(x: 16, y: 381, width: screenSize.width - 16, height: frontHeaderTextHeight[0])
        frontLayer.addSublayer(frontHeaderText)


    //UILabel
    let rearHeaderText = UILabel()
   rearHeaderText.attributedText = textHeader
        rearHeaderText.textAlignment = .left
        rearHeaderText.lineBreakMode = NSLineBreakMode.byWordWrapping
        rearHeaderText.numberOfLines = 0
        rearHeaderText.frame = CGRect(x: 16, y: 381, width: screenSize.width - 16, height: frontHeaderTextHeight[0])
        rearLayer.addSubview(rearHeaderText)

//计算标签的高度     func getLabelHeight(text:String,font:UIFont,lineNumber:Int) - > CGFloat的{

    let label = UILabel()

    label.frame = CGRect(x: 0, y: 0, width: screenSize.width - 32, height: 100)
    label.text = text
    label.font = font
    label.textAlignment = NSTextAlignment.left
    label.numberOfLines = lineNumber;

    label.sizeToFit()

    return label.frame.height

}

0 个答案:

没有答案