为其轮廓创建 Box 后 UITextView 的大小和位置错误

wrong size and positon of UITextView after creating Box for its contours

我正在尝试通过 boundingrectwithsize 函数将测试包装到封闭框中。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if let messageText = messages?[indexPath.item].text {
        let size = CGSize(width:view.frame.width,height: 1000)
        let options = NSStringDrawingOptions.usesLineFragmentOrigin.union(.usesFontLeading)
        let estimatedFrame = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 18)], context: nil)
        return CGSize(width: view.frame.width,height: estimatedFrame.height)
    }

    return CGSize(width:view.frame.width,height: 100)
}

}

但是输出有点奇怪,我很困惑

为什么总是剪掉最后一根弦?在我看来,我使用的是正确的 NSString.DrawingOptions,尤其是 usesFontLeading 计算了大小,但为什么它切断了最后一个字符串?

UITextView 默认添加填充。使用 NSString 大小调整方法进行大小调整不会考虑到这一点。您可以使用以下方式关闭填充:

myTextView.textContainerInset = UIEdgeInsets.zero
myTextView.textContainer.lineFragmentPadding = 0

或将它们添加到您的尺码中:

CGSize(width: view.frame.width,height: estimatedFrame.height + myTextView.textContainerInset.top + myTextView.textContainerInset.bottom)