ios - Swift:如何计算居中字符串的大小
<p><p>我目前计算字符串的大小,如下所示。如何计算居中字符串?</p>
<pre><code>func sizeOfString (string: String, constrainedToWidth width: Double, font: UIFont) -> CGSize {
return (string as NSString).boundingRect(with: CGSize(width: width, height: Double.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: ,
context: nil).size
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>你说:</p>
<blockquote>
<p>Something else must be effecting the result because the string goes to 2 lines approximately two characters before it is calculated as doing so.</p>
</blockquote>
<p>是的,如果你自己渲染 <code>boundingRect</code> 将捕获字符串的大小(例如使用 <code>draw(in:withAttributes:)</code>。但是 <code>UILabel</code> 可以想象做各种各样的其他事情(从边缘插入等)。</p>
<p>令我震惊的是,您有两个基本选择:</p>
<ol>
<li><p>现在,您可以获取 Collection View 流布局的布局并将其 <code>itemSize</code> 设置为 <code>UICollectionViewFlowLayoutAutomaticSize</code>(在 iOS 10 及更高版本中):</p>
<pre><code>let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = UICollectionViewFlowLayoutAutomaticSize
layout.estimatedItemSize = ...
</code></pre>
<p>然后单元格将根据您在单元格中的自动布局约束自动调整大小(例如,标签的固定宽度,允许固有尺寸控制高度,也许尺寸 <= 一些最大尺寸)。</p></li>
<li><p>如果您想自己计算 <code>boundingRect</code>,那么您可能会使用 <a href="https://developer.apple.com/documentation/foundation/nsstring/1529855-draw" rel="noreferrer noopener nofollow"><code>draw(in:withAttributes:)</code></a> 自己渲染它,也避免了 <code>UILabel</code> 在幕后所做的任何特殊行为:</p>
<pre><code>let string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam quis leo convallis, euismod ipsum sed, lacinia diam. Nam sit amet justo id lacus blandit sodales id et."
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .center
let attributes: = [
.font: font,
.paragraphStyle: paragraphStyle
]
let rect = string.boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: attributes,
context: nil)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
string.draw(in: rect, withAttributes: attributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
</code></pre>
<p>然后您可以将 <code>image</code> 和 <code>rect</code> 用于 <code>UIImageView</code>。</p></li>
</ol></p>
<p style="font-size: 20px;">关于ios - Swift:如何计算居中字符串的大小,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/46453019/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/46453019/
</a>
</p>
页:
[1]