Ios Swift:如何计算居中字符串的大小
我目前计算字符串的大小,如下所示。如何计算居中字符串Ios Swift:如何计算居中字符串的大小,ios,swift,string,Ios,Swift,String,我目前计算字符串的大小,如下所示。如何计算居中字符串 func sizeOfString (string: String, constrainedToWidth width: Double, font: UIFont) -> CGSize { return (string as NSString).boundingRect(with: CGSize(width: width, height: Double.greatestFiniteMagnitude),
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: [NSFontAttributeName: font],
context: nil).size
}
Objective-C版本
UIFont *font = [UIFont fontWithName:@"Helvetica" size:30];
NSDictionary *userAttributes = @{NSFontAttributeName: font,
NSForegroundColorAttributeName: [UIColor blackColor]};
NSString *text = @"hello";
...
const CGSize textSize = [text sizeWithAttributes: userAttributes];
Swift版本:
extension String {
func size(OfFont font: UIFont) -> CGSize {
return (self as NSString).size(attributes: [NSFontAttributeName: font])
}
}
用法:
let string = "hello world!"
let font = UIFont.systemFont(ofSize: 12)
let width = string.size(OfFont: font).width // size: {w: 98.912 h: 14.32}
你说:
一定是其他因素影响了结果,因为在计算字符串之前,该字符串将进入大约两个字符的两行
是的,boundingRect
将捕获字符串的大小,如果您自己渲染它(例如,使用draw(in:withAttributes:)
。但是UILabel
可以做其他各种事情(从边缘插入,等等)
我觉得你有两个基本的选择:
itemSize
设置为UICollectionViewFlowLayoutAutomaticSize
(在iOS 10及更高版本中):
然后,将根据单元格中的自动布局约束自动调整单元格的大小(例如,标签的固定宽度,允许内部大小控制高度,可能是大小)“居中字符串的大小”是什么意思?居中字符串的大小应该与不居中字符串的大小相同。你完全正确,@Rob。请原谅我的高级时刻。一定是其他因素影响了结果,因为在计算之前,字符串会进入大约两个字符的两行。我应该提一下,字符串被设置为集合视图单元格中标签的文本。我提供的宽度是视图的宽度,减去单元格的左、右部分插入以及标签的前导和尾随空格。他希望指定最大宽度,并计算换行时的高度。以上仅适用于单行文本。
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = UICollectionViewFlowLayoutAutomaticSize
layout.estimatedItemSize = ...
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: [NSAttributedStringKey: Any] = [
.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()