我需要画一个带有划线的UILabel。因此,我将UILabel子类化并按如下方式实现它:
@implementation UIStrikedLabel
- (void)drawTextInRect:(CGRect)rect{
[super drawTextInRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextFillRect(context,CGRectMake(0,rect.size.height/2,rect.size.width,1));
}
@end
发生的情况是,UILabel被划过一行,与整个标签一样长,但文本可以更短。有没有一种方法可以确定文本的像素长度,以便可以适当地绘制线条?
我也对任何其他解决方案持开放态度,如果知道的话:)
最好的,埃里克
发布于 2009-08-27 12:37:10
NSString有一个可用于此的sizeWithAttributes:方法。它返回一个CGSize结构,因此您可以执行类似于下面的操作来查找标签中文本的宽度。
iOS 7及更高版本
CGSize textSize = [[label text] sizeWithAttributes:@{NSFontAttributeName:[label font]}];
CGFloat strikeWidth = textSize.width;
iOS <7
在iOS7之前,您必须使用sizeWithFont:方法。
CGSize textSize = [[label text] sizeWithFont:[label font]];
CGFloat strikeWidth = textSize.width;
UILabel有一个字体属性,您可以使用它来动态获取标签的字体详细信息,就像我上面所做的那样。
希望这能有所帮助:)
发布于 2020-09-18 14:36:36
这将会起作用。试试看
NSDictionary *attrDict = @{NSFontAttributeName : [GenericUtility getOpenSansRegularFontSize:12]};
CGSize stringBoundingBox = [selectedReservationModel.DateLabel sizeWithAttributes: attrDict];
lblDeliveryDateWidth = stringBoundingBox.width;
https://stackoverflow.com/questions/1340667
复制相似问题