带有“+”文本的UILabel不会垂直居中

时间:2013-09-17 16:50:15

标签: ios objective-c uilabel

enter image description here

self.iconLabel.frame = self.contentView.frame;

self.iconLabel.font = [UIFont systemFontOfSize:100.0];
self.iconLabel.text = @"+";
self.iconLabel.textColor = [UIColor blackColor];
self.iconLabel.textAlignment = NSTextAlignmentCenter;

因此UILabel的框架与其容器视图的大小相同,self.contentView

我也需要“+”垂直居中,我希望它在中心。

我怎样才能做到这一点?

我唯一的想法是将iconLabel.frame向上移动。

编辑:从self.iconImageView更改为self.contentView,它是UIViewUILabel位于self.iconImageView上方,UIImageView

编辑2:尝试实现kshitij godara的代码,结果是:

enter image description here

我稍微修改了代码:

CGSize constraint = CGSizeMake(self.contentView.frame.size.width, self.contentView.frame.size.height);

NSString *str = @"+";

UIFont *myFont = [UIFont systemFontOfSize:100.0];

CGSize stringSize = [str sizeWithFont:myFont constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

self.iconLabel.frame = CGRectMake(0, 0, stringSize.width, stringSize.height);
self.iconLabel.font = myFont;
self.iconLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.iconLabel.numberOfLines = 0;
[self.iconLabel sizeToFit];
self.iconLabel.text = str;

编辑3:

框架非常大:

enter image description here

2 个答案:

答案 0 :(得分:4)

这可能是字体本身的问题。每种字体都定义了它的形状,行为,排版等。字体似乎是视觉垂直中心的定位字符“+”。您可以在包含字母“+”,“dog + Cat”的任何其他字符串上进行测试。 “+”字母可能会在图像底部附近绘制。

从我的角度来看,你有两个选择:

  • 使用图标图片代替“+”符号。这将是最简单和最佳的工作解决方案
  • 使用自定义字体编辑,使其在视觉上看起来完全符合您的需要(字母“+”完全以其排版为中心)。这个可能是非常痛苦和耗时的选择

编辑:关于第二个选项:我已经完成了这样的程序来修复this tutorial之后的一些错位字体。但它仍然只修复整个字体,而不是单个字符

答案 1 :(得分:0)

您可以这样做 - 尝试应用此

CGSize constraint = CGSizeMake(iconImageFrame.size.width,1000.0f);

//Now Calculate size of string 

NSString *str = @"+";

//Always give the same font to calculate size which you giving for label 

UIFont *myFont = [UIFont systemFontOfSize:100.0];

CGSize stringSize = [str sizeWithFont:myFont 
                           constrainedToSize:constraint
                               lineBreakMode:UILineBreakModeWordWrap];
//now set same font for uilabel and also make it to fit to size 
//like this

UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(myIconLabelFrame.x,myIconLabelFrame.y,stringSize.width,stringSize.height)];

myLabel.font = myFont;
myLabel.lineBreakMode = UILineBreakModeWordWrap;
myLabel.numberOfLines = 0;
[myLabelsizeToFit];
myLabel.text = str;

由于现在标签尺寸完全合适,因此它始终位于中心。此代码也可用于动态增加标签的高度。 我希望它能解决你的问题。谢谢!

相关问题