我有一个UILabel
,它的长度可以根据我的应用程序在iPhone或iPad上是以纵向模式还是横向模式运行而变化。当文本太长,无法显示在一行上,并且它被截断时,我希望用户能够按下它,并获得完整文本的弹出窗口。
如何检查UILabel
是否正在截断文本?这有可能吗?现在我只是根据我所处的模式检查不同的长度,但它不能很好地工作。
发布于 2010-06-20 04:34:59
您可以计算width of the string并查看宽度是否大于label.bounds.size.width
NSString UIKit Additions有几种方法可以计算具有特定字体的字符串的大小。但是,如果您的标签具有允许系统将文本缩小到该大小的minimumFontSize。在这种情况下,您可能希望使用sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:。
CGSize size = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];
if (size.width > label.bounds.size.width) {
...
}
发布于 2015-07-17 00:29:59
Swift (as扩展)-适用于多行uilabel:
swift4:( boundingRect
的attributes
参数略有变化)
extension UILabel {
var isTruncated: Bool {
guard let labelText = text else {
return false
}
let labelTextSize = (labelText as NSString).boundingRect(
with: CGSize(width: frame.size.width, height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [.font: font],
context: nil).size
return labelTextSize.height > bounds.size.height
}
}
swift3:
extension UILabel {
var isTruncated: Bool {
guard let labelText = text else {
return false
}
let labelTextSize = (labelText as NSString).boundingRect(
with: CGSize(width: frame.size.width, height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
return labelTextSize.height > bounds.size.height
}
}
swift2:
extension UILabel {
func isTruncated() -> Bool {
if let string = self.text {
let size: CGSize = (string as NSString).boundingRectWithSize(
CGSize(width: self.frame.size.width, height: CGFloat(FLT_MAX)),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: self.font],
context: nil).size
if (size.height > self.bounds.size.height) {
return true
}
}
return false
}
}
发布于 2012-10-26 12:41:49
您可以使用UILabel创建一个类别
- (BOOL)isTextTruncated
{
CGRect testBounds = self.bounds;
testBounds.size.height = NSIntegerMax;
CGRect limitActual = [self textRectForBounds:[self bounds] limitedToNumberOfLines:self.numberOfLines];
CGRect limitTest = [self textRectForBounds:testBounds limitedToNumberOfLines:self.numberOfLines + 1];
return limitTest.size.height>limitActual.size.height;
}
https://stackoverflow.com/questions/3077109
复制相似问题