2

我想在视图的顶部中心设置一个标签,我已经尝试过了

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(self.myView.center.x, 25, 92, 46)];

但它不像我想要的那样在中心,这是它的样子:http://i49.tinypic.com/e17mty.png

我想要标签的中间,在 x 中心,而不是标签的开头在中心。

4

8 回答 8

1

最简单的方法是使标签的框架宽度等于视图的框架宽度,并将标签的对齐方式设置为中心。

希望这可以帮助 !!!

于 2013-03-12T08:36:42.663 回答
1

像这样试试

UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
    lbl.textAlignment=UITextAlignmentCenter;
于 2013-03-12T08:39:53.053 回答
0

尝试将正确的 x 位置设置为view.center.x - (labelwidth/2). 还将 设置textAlignmentcenter

于 2013-03-12T08:35:43.727 回答
0

像这样使用CGPointMake标签的设置中心。

lblAppTitle.center= CGPointMake(self.view.bounds.size.width / 2, 25);
[lblAppTitle setTextAlignment:NSTextAlignmentCenter];
于 2013-03-12T08:37:41.010 回答
0

设置它的中心而不是设置矩形

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, 92, 46)];
label.center = self.myView.center;
//Also if your frame is bigger than text then you can set this also
label.textAlignment = UITextAlignmentCenter;
于 2013-03-12T08:42:26.770 回答
0

试试这个

int x=(self.myView.frame.size.width-92)/2;
UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(x, 25, 92, 46)];
lbl.textAlignment=UITextAlignmentCenter;
于 2013-03-12T08:43:05.200 回答
0

试试这个:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 92, 46)];
label.center = CGPointMake(label.bounds.size.width / 2, 25);

或这个:

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(self.myView.center.x - 46, 25, 92, 46)];
于 2013-03-12T08:46:43.520 回答
0

它完全按照您的程序进行。不幸的是,在 UI 编程中总是涉及到一些基本的数学。

一种可能的解决方案:使用任何位置但大小合适的框架对其进行初始化。然后相应地设置标签视图的中心属性。

[label setCenter:CGPointMake(self.myView.center.x, 25)];

或者只是以某种方式设置框架,它占用了 myView 从左到右的所有空间,并将文本对齐设置为 NSTextAlignmentCenter。

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, self.myView.frame.size.width, 46)];
label.textAlignment = NSTextAlignmentCenter;

或者相应地计算左上角并在初始化时设置框架。使用中心位置并减去一半的宽度。或者使用 myView 的完整 with,减去 with 然后除以 2。

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(self.myView.center.x-92/2, 25, 92, 46)];

或者

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((self.myView.frame.width-92)/2, 25, 92, 46)];
于 2013-03-12T08:48:53.123 回答