Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/101.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios UILabel未在我的UIView中居中_Ios_Objective C_Iphone_Layout_Uiview - Fatal编程技术网

Ios UILabel未在我的UIView中居中

Ios UILabel未在我的UIView中居中,ios,objective-c,iphone,layout,uiview,Ios,Objective C,Iphone,Layout,Uiview,我在初始化时将UILabel添加到UIView中,而标签不会居中。我已经尝试过将它置于LayoutSubView的中心,并以编程方式添加约束,但没有成功。当它出现时,它位于中心左侧约200像素处。这是我的密码。提前谢谢 - (instancetype)initWithTitle:(NSString *)title andBody:(NSString *)body Andwidth:(CGFloat)width { self = [super initWithFrame:CGRectMake(0,

我在初始化时将UILabel添加到UIView中,而标签不会居中。我已经尝试过将它置于LayoutSubView的中心,并以编程方式添加约束,但没有成功。当它出现时,它位于中心左侧约200像素处。这是我的密码。提前谢谢

- (instancetype)initWithTitle:(NSString *)title andBody:(NSString *)body Andwidth:(CGFloat)width {
self = [super initWithFrame:CGRectMake(0, 0, width, 60)];
if (self) {

    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, 60)];
    containerView.backgroundColor = [UIColor orangeColor];
    [self addSubview:containerView];

    self.winningLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 300, 40)];
    self.winningLabel.textColor = [UIColor whiteColor];
    self.winningLabel.font = [UIFont fontWithName:@"Avenir" size:30];
    self.winningLabel.backgroundColor = [UIColor clearColor];
    self.winningLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    self.winningLabel.numberOfLines = 2;
    self.winningLabel.text = @"YOU WIN";
    self.winningLabel.hidden = YES;
    [containerView addSubview:self.winningLabel];

    NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:self.winningLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    [self addConstraint:xCenterConstraint];

    NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:self.winningLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    [self addConstraint:yCenterConstraint];

}

    return self;
}

- (void)layoutSubviews {
    [self.winningLabel setCenter:self.center];
}

我想你忘了文本对齐。默认情况下,标签中的文本向左对齐。如果希望它位于中心,则应明确指定它

self.winningLabel.textAlignment = NSTextAlignmentCenter;