Centering a label in a UIView

前端 未结 2 1452
[愿得一人]
[愿得一人] 2021-02-15 18:04

What\'s the best way to center a label in a UIView? If you do something such as

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(view.fr         


        
相关标签:
2条回答
  • 2021-02-15 18:53

    The main thing you are doing wrong is taking half the origin values, rather than half the sizes

    However, you don't need to even calculate that in this case - just do something like the following:

    
    UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
    aView.backgroundColor = [UIColor darkGrayColor];
    
    UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 125, 30)];
    aLabel.center = aView.center;
    

    (note, you don't need to force those coordinates to floats - in this case writing them as ints seems more readable).

    Also, it's a matter of style - but since you're already using property syntax (aView.backgroundColor) you may as well use it for the center property too :-)

    0 讨论(0)
  • 2021-02-15 18:58

    To position any child horizontally centered in a parent you would calculate its position like so;

    childX = (parentWidth - childWidth) / 2
    

    (This also applies to height).

    0 讨论(0)
提交回复
热议问题