对于想了解在Swift中根据String计算UILabel的大小的读者,本文将是一篇不可错过的文章,我们将详细介绍swift获取字符串长度,并且为您提供关于iOSswift带有attributeStr
对于想了解在 Swift 中根据 String 计算 UILabel 的大小的读者,本文将是一篇不可错过的文章,我们将详细介绍swift获取字符串长度,并且为您提供关于iOS swift 带有attributeString的多行文本label、ios – swift:以编程方式创建UILabel固定宽度,根据文本长度垂直调整大小、ios – 从UILabel Swift中获取一个Int、ios – 使用swift在UILabel中单击事件的NSAttributedString的有价值信息。
本文目录一览:- 在 Swift 中根据 String 计算 UILabel 的大小(swift获取字符串长度)
- iOS swift 带有attributeString的多行文本label
- ios – swift:以编程方式创建UILabel固定宽度,根据文本长度垂直调整大小
- ios – 从UILabel Swift中获取一个Int
- ios – 使用swift在UILabel中单击事件的NSAttributedString
在 Swift 中根据 String 计算 UILabel 的大小(swift获取字符串长度)
我正在尝试根据不同的字符串长度计算 UILabel 的高度。
func calculateContentHeight() -> CGFloat{ var maxLabelSize: CGSize = CGSizeMake(frame.size.width - 48, CGFloat(9999)) var contentNSString = contentText as NSString var expectedLabelSize = contentNSString.boundingRectWithSize(maxLabelSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(16.0)], context: nil) print("\(expectedLabelSize)") return expectedLabelSize.size.height}
以上是我用来确定高度的当前函数,但它不起作用。我将非常感谢我能得到的任何帮助。我更喜欢 Swift 而不是 Objective C 中的答案。
答案1
小编典典使用扩展String
斯威夫特 3
extension String { func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(boundingBox.height) } func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(boundingBox.width) }}
还有 on NSAttributedString
(有时非常有用)
extension NSAttributedString { func height(withConstrainedWidth width: CGFloat) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil) return ceil(boundingBox.height) } func width(withConstrainedHeight height: CGFloat) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil) return ceil(boundingBox.width) }}
斯威夫特 4 & 5
只需更改方法attributes
中的值extension String
从
[NSFontAttributeName: font]
至
[.font : font]
iOS swift 带有attributeString的多行文本label
class AttributeStringGenerator {
var attributeString: NSMutableAttributedString!
var lineSpacing: CGFloat = 2
init() {
attributeString = NSMutableAttributedString()
}
func reset() {
attributeString = NSMutableAttributedString()
}
/// 添加空行
func addEmptyLine(height: CGFloat = 12) {
let font = UIFont.systemFont(ofSize: height)
let attr = NSAttributedString(string: "\n", attributes: [NSAttributedString.Key.font:font])
attributeString.append(attr)
}
/// 加一行文字
///
/// - Parameters:
/// - string: 要加的文字
/// - alignment: 对齐方式
/// - color: 颜色
/// - font: 字体
/// - isLastLine: 是否最后一行,最后一行不加换行
func addLine(string: String, alignment: NSTextAlignment, color: UIColor = UIColor.white, font: UIFont = UIFont.systemFont(ofSize: 12), isLastLine: Bool = false) {
let para = NSMutableParagraphStyle()
para.alignment = alignment
para.lineSpacing = lineSpacing
//如果是最后一行,不需要加 \n
var s = string
if !isLastLine {
s += "\n"
}
let attr = NSAttributedString(string: s, attributes:
[NSAttributedString.Key.paragraphStyle:para,
NSAttributedString.Key.foregroundColor:color,
NSAttributedString.Key.font:font])
attributeString.append(attr)
}
/// 添加文字居中带图标的行
///
/// - Parameters:
/// - icon: 图标
/// - string: 文字
/// - size: 图标大小
/// - color: 文字颜色
/// - font: 字体
/// - isLastLine: 是否最后一行
func addLineWith(icon: UIImage,string: String, size: CGSize, color: UIColor = UIColor.white, font: UIFont = UIFont.systemFont(ofSize: 18), isLastLine: Bool = true) {
let para = NSMutableParagraphStyle()
para.alignment = .center
para.lineSpacing = lineSpacing
//如果是最后一行,不需要加 \n
var s = string
if !isLastLine {
s += "\n"
}
let att = NSTextAttachment(data: nil, ofType: nil)
att.image = icon
att.bounds = CGRect(x: 0, y: -font.pointSize/10, width: size.width, height: size.height)
let attr = NSMutableAttributedString(attributedString: NSAttributedString(attachment: att))
attr.append(NSMutableAttributedString(string: " " + s, attributes:
[NSAttributedString.Key.foregroundColor:color,
NSAttributedString.Key.font:font]))
attr.addAttribute(NSAttributedString.Key.paragraphStyle, value: para, range: NSMakeRange(0, attr.length))
attributeString.append(attr)
}
/// 添加一行文字,分左中右三部分, 左边的左对齐, 中间的右对齐,可以设置通过某符号对齐,比如 ":", 右边的可以自行设置对齐方式
///
/// - Parameters:
/// - leftString: 左边的文字
/// - leftColor: 左边文字的颜色
/// - leftFont: 左边文字字体
/// - centerString: 中间的文字
/// - centerPosition: 中间文字的位置
/// - centerColor: 中间文字颜色
/// - centerFont: 中间文字字体
/// - alignString: 中间文字对齐的符号
/// - rightString: 右边的文字
/// - rightPosition: 右边文字的位置
/// - rightColor: 右边文字颜色
/// - rightFont: 右边文字字体
/// - alignment: 右边文字对齐方式
func addLine(leftString: String?, leftColor: UIColor = UIColor.white, leftFont: UIFont = UIFont.systemFont(ofSize: 12),
centerString: String? = nil,centerPosition:CGFloat = 0, centerColor: UIColor = UIColor.white, centerFont: UIFont = UIFont.systemFont(ofSize: 12), alignString: String = "",
rightString: String?,rightPosition:CGFloat = 0, rightColor: UIColor = UIColor.white, rightFont: UIFont = UIFont.systemFont(ofSize: 12), alignment: NSTextAlignment = .right,
isLastLine: Bool = false) {
var string = ""
var leftRange: NSRange
var centerRange: NSRange
var rightRange: NSRange
if let left = leftString {
string = string + left + "\t"
//特殊字符.count算出的长度不对,需要改成 lengthOfBytes(using: String.Encoding.unicode)/2
leftRange = NSMakeRange(0, string.lengthOfBytes(using: String.Encoding.unicode)/2)
} else {
string += "\t"
leftRange = NSMakeRange(0, 1)
}
if let center = centerString {
string = string + center + "\t"
centerRange = NSMakeRange(leftRange.length, center.lengthOfBytes(using: String.Encoding.unicode)/2 + 1)
} else {
//string += "\t"
centerRange = NSMakeRange(leftRange.length, 0)
}
if let right = rightString {
if isLastLine {
string = string + right
rightRange = NSMakeRange(leftRange.length + centerRange.length, right.lengthOfBytes(using: String.Encoding.unicode)/2)
} else {
string = string + right + "\n"
rightRange = NSMakeRange(leftRange.length + centerRange.length, right.lengthOfBytes(using: String.Encoding.unicode)/2 + 1)
}
} else {
if isLastLine {
string += "\n"
rightRange = NSMakeRange(leftRange.length + centerRange.length, 1)
} else {
rightRange = NSMakeRange(leftRange.length + centerRange.length, 0)
}
}
let para = NSMutableParagraphStyle()
para.lineSpacing = lineSpacing
let align = NSCharacterSet(charactersIn: alignString)
let t1 = NSTextTab(textAlignment: .right, location: centerPosition, options: [NSTextTab.OptionKey.columnTerminators:align])
let t2 = NSTextTab(textAlignment: alignment, location: rightPosition, options: [:])
para.tabStops = [t1,t2]
if centerString == nil {
para.tabStops = [t2]
}
let attr = NSMutableAttributedString(string: string)
attr.addAttribute(NSAttributedString.Key.paragraphStyle, value: para, range: NSMakeRange(0, string.count))
attr.addAttributes([NSAttributedString.Key.foregroundColor:leftColor, NSAttributedString.Key.font:leftFont], range: leftRange)
attr.addAttributes([NSAttributedString.Key.foregroundColor:centerColor, NSAttributedString.Key.font:centerFont], range: centerRange)
attr.addAttributes([NSAttributedString.Key.foregroundColor:rightColor, NSAttributedString.Key.font:rightFont], range: rightRange)
attributeString.append(attr)
}
func getHeight(width:CGFloat) -> CGFloat {
let options : NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
let bounds = attributeString.boundingRect(with: CGSize(width: width, height: 99999), options: options, context: nil)
return bounds.height
}
}
最后将attributeString赋值给label
ios – swift:以编程方式创建UILabel固定宽度,根据文本长度垂直调整大小
示例(忽略颜色)
>短文本(注意与较长文本相同的宽度):
>更长的文本(注意与较短文本示例相同的宽度,并且添加更多行的文本):
如果文本可以适合固定宽度的一行,则标签不需要垂直调整大小.但是如果有更多字符,标签应该保持垂直扩展以适应这些附加字符.文本应该一行一行地包裹.文本应从标签的左上角开始.
更具体:
let marker = GMSMarker(position: myLatLng) // see https://stackoverflow.com/a/40211383/1168364 for imageWithView marker.icon = imageWithView(label) // **how do i create this label?** marker.map = map // map is a GMSMapView
这些标签可以在屏幕上的任何位置.这适用于地图应用程序,其中每个标签将放置在随机位置.标签的位置彼此没有关系.
解决方法
第一个将视图调整为最小尺寸以适合子视图的内容,第二个视图根本不更改帧,但返回计算的大小:(1)适合所有子视图和(2)不超过参数大小
所以你可以使用sizeThatFits:
let label = UILabel() override func viewDidLoad() { super.viewDidLoad() label.backgroundColor = UIColor.orange label.textColor = UIColor.white // label.text = "ultimate Frisbee" label.text = "ultimate Frisbee\nin 3 minutes,\nall welcome|2" label.numberOfLines = 10 view.addSubview(label) updateLabelFrame() } func updateLabelFrame() { let maxSize = CGSize(width: 150,height: 300) let size = label.sizeThatFits(maxSize) label.frame = CGRect(origin: CGPoint(x: 100,y: 100),size: size) }
输出:
附:您也可以通过自动布局约束解决您的问题,但我不是以编程方式使用它们的忠实粉丝.
ios – 从UILabel Swift中获取一个Int
@IBAction func NumberInput(sender: UIButton) { var input:Int = sender.titleLabel as Int }
解决方法
if let input = sender.titleLabel?.text?.toInt() { // do something with input } else { // The label Couldn't be parsed into an int }
但是,我建议使用UIView.tag或子类化UIButton并为其添加Int属性来实现此目的,以防您更改标签的显示.
ios – 使用swift在UILabel中单击事件的NSAttributedString
我将此字符串放在UILabel中.
现在当用户点击“登录!”时,当前的viewController应该转到另一个viewController,或者在点击登录时调用某个函数.
任何代码或建议都应该没问题.
解决方法
class ViewController: UIViewController,UITextViewDelegate { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() let text = NSMutableAttributedString(string: "Already have an account? ") text.addAttribute(NSFontAttributeName,value: UIFont.systemFontOfSize(12),range: NSMakeRange(0,text.length)) let selectablePart = NSMutableAttributedString(string: "Sign in!") selectablePart.addAttribute(NSFontAttributeName,selectablePart.length)) // Add an underline to indicate this portion of text is selectable (optional) selectablePart.addAttribute(NSUnderlinestyleAttributeName,value: 1,selectablePart.length)) selectablePart.addAttribute(NSUnderlineColorAttributeName,value: UIColor.blackColor(),selectablePart.length)) // Add an NSLinkAttributeName with a value of an url or anything else selectablePart.addAttribute(NSLinkAttributeName,value: "signin",selectablePart.length)) // Combine the non-selectable string with the selectable string text.appendAttributedString(selectablePart) // Center the text (optional) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = NSTextAlignment.Center text.addAttribute(NSParagraphStyleAttributeName,value: paragraphStyle,text.length)) // To set the link text color (optional) textView.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.blackColor(),NSFontAttributeName: UIFont.systemFontOfSize(12)] // Set the text view to contain the attributed text textView.attributedText = text // disable editing,but enable selectable so that the link can be selected textView.editable = false textView.selectable = true // Set the delegate in order to use textView(_:shouldInteractWithURL:inRange) textView.delegate = self } func textView(textView: UITextView,shouldInteractWithURL URL: NSURL,inRange characterRange: NSRange) -> Bool { // **Perform sign in action here** return false } }
关于在 Swift 中根据 String 计算 UILabel 的大小和swift获取字符串长度的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于iOS swift 带有attributeString的多行文本label、ios – swift:以编程方式创建UILabel固定宽度,根据文本长度垂直调整大小、ios – 从UILabel Swift中获取一个Int、ios – 使用swift在UILabel中单击事件的NSAttributedString等相关知识的信息别忘了在本站进行查找喔。
本文标签: