如何在框架中水平居中(上/下)UILabel文本



我有一个UILabel,从一个简单的控件子类化。我遇到的问题是标签中的文本被格式化到其框架的左上角。通常情况下,UILabel文本将在框架中水平居中,而不是一直靠在顶部。

我需要有文本水平居中(上/下)在我的UILabel。我该怎么做才能实现呢?

我有代码张贴在下面,显示我在做什么和UILabel是一个出口属性在我的故事板视图控制器上的对象。我在这个标签上设置了约束,这样它就可以动态地适应它的父视图。

- (void)setTitleForCell:(NSString *)title
{
    [self.titleLabel setText:title];
    UIColor *titleColor = [UIColor darkGrayColor];
    NSMutableParagraphStyle *titleParagraphStyle = [[NSMutableParagraphStyle alloc] init];
    [titleParagraphStyle setAlignment:NSTextAlignmentLeft];
    [titleParagraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
    NSDictionary *titleAttributes = [NSDictionary dictionaryWithObjectsAndKeys:titleColor, NSForegroundColorAttributeName, [UIFont fontWithName:@"HelveticaNeue-Light" size:13.0f], NSFontAttributeName, titleParagraphStyle, NSParagraphStyleAttributeName, nil];
    [self.titleLabel setAttributes:titleAttributes];
    NSDictionary *handleAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor lightGrayColor], NSForegroundColorAttributeName, [UIFont fontWithName:@"HelveticaNeue-Light" size:13.0f], NSFontAttributeName, nil];
    NSDictionary *hashtagAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor lightGrayColor], NSForegroundColorAttributeName, [UIFont fontWithName:@"HelveticaNeue-Light" size:13.0f], NSFontAttributeName, nil];
    [self.titleLabel setAttributes:handleAttributes hotWord:STTweetHandle];
    [self.titleLabel setAttributes:hashtagAttributes hotWord:STTweetHashtag];
    [self.titleLabel setDetectionBlock:^(STTweetHotWord hotWord, NSString *string, NSString *protocol, NSRange range) {
        NSArray *hotWords = @[@"Handle", @"Hashtag", @"Link"];
        if (hotWord == STTweetHandle) {
        }
    }];
}

我还设置了框架的背景颜色,这样我就可以看到它是如何设置的,但它就像我想的那样,文字尽可能地与顶部对齐。正文下面还有很多空白处。

我建议您更改标签的约束方式,使其高度不固定(当您从顶部指定0时,从底部指定0 -高度固定为单元格的高度),并且它垂直地在容器中居中。

作为旁注:当排除布局问题时,我发现将临时背景颜色设置为各种明亮的颜色非常有用(例如,cell为绿色,title为蓝色),这样可以清楚地看到每个视图占用的框架。

最新更新