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

标签 ios swift nsstring

我正在尝试通过 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)
}

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

enter image description here

为什么它总是切断最后一根弦?在我看来,我使用的是正确的 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)

关于ios - 为其轮廓创建 Box 后 UITextView 的大小和位置错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48476969/

相关文章:

ios - UITableViewCell 中的 UIPageControl 和 UIScrollView

ios - 如何从 UICollectionView 弹出一个 uicollectionViewCell?

iphone - iOS 7多空格问题

ios - 如何在 iOS7 中搜索 NSString 句子中用逗号分隔的特定单词?

iOS Google Maps SDK 不显示用户位置

ios - 使用 iOS 动态压缩二维数组

swift - 无法将数据添加到 firebase

ios - 核心位置不征求许可

ios - NSLocalized 从字符串文件创建不同的字符串

ios - TableViewController 中 SearchBar 中的取消按钮需要双击