How to center a UILabel on UIView

前端 未结 7 1983
日久生厌
日久生厌 2020-12-13 06:12

How can I center the UILabel on the UIView? I am using the following code

float width = weatherView.bounds.size.width; 
float height = weatherView.bounds.siz         


        
相关标签:
7条回答
  • 2020-12-13 06:39

    How about:

    [self.label setCenter:view.center];
    
    0 讨论(0)
  • 2020-12-13 06:44

    If the label is a subview of view:

    [self.label setCenter:CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2)]
    

    Don't use view.center unless the label and view have the same superview.

    If there is no immediate connection, then you'll have to transform view's center to the coordinate space of label's parent. Then you could use PengOne's answer with the transformed point.

    0 讨论(0)
  • 2020-12-13 06:44

    A better posible solution is:

    First: If you are doing this programmatically you'll need to initialize with frame and some customizations:

    // Simple example
    int yPosition = 10;
    UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0, yPosition, self.view.frame.size.width, 0)];
    [label setText: @"Testing..."];
    [label setBackgroundColor: [UIColor clearColor]];
    [label setNumberOfLines: 0];
    [label sizeToFit];
    

    Second: If a label what you are trying to center you can just run this after setNumberOflines selector called and 0 value assigned, your text will have all lines needed, and sizeToFit method called to have a good customization, and finally:

    [self.label setCenter: CGPointMake(self.view.center.x, self.label.center.y)];
    

    This will center only the X axis, and the Y axis will stay as you desired in the frame initialization.

    PS: It's also valid if not a UILabel but depends on the control you are using will need another simple customization or neither, and if you only want to center programmatically but interface builder designed, just need to run the second code.

    0 讨论(0)
  • 2020-12-13 06:55

    There are two possibility if your UILabel is added via .xib or else added programmatically .

    If first case i.e added via .xib then you can set the position from xib file size inspector tab with the 'Arrange' property

    And if second case persist then you can set as --- [self.label setCenter:view.center];

    0 讨论(0)
  • 2020-12-13 06:58

    Use NSTextAlignmentCenter if what you have is the label already set and you want to center its content.

    cell.menuLabel.textAlignment = NSTextAlignmentCenter;
    
    0 讨论(0)
  • 2020-12-13 07:00

    PengOne / Alex Lockwood's answer is simple and useful. If you intend to support rotation, add the following to keep it centered:

    [self.myLabel setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
    
    0 讨论(0)
提交回复
热议问题