How to center a UILabel on UIView

前端 未结 7 1994
日久生厌
日久生厌 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条回答
  •  萌比男神i
    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.

提交回复
热议问题