【问题标题】:How to center UILabel text horizontally (Up/Down) in frame?如何在框架中水平(向上/向下)居中 UILabel 文本?
【发布时间】:2014-05-02 21:50:29
【问题描述】:

我有一个从simple control. 子类化的 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) {

        }
    }];
}

我还将框架的背景设置为一种颜色,以便我可以看到它是如何设置的,但就像我想的那样,文本尽可能地与顶部对齐。文字下方仍有大量空间。

【问题讨论】:

  • 检查文本末尾是否没有换行符。
  • 您的意思是垂直居中(上/下)。水平方向是左/右。
  • 您对该标签有什么限制?我认为 UILabel 不会将其内容垂直居中。
  • @sha 我的 UILabel 被设置到一个 UITableViewCell 中,并且它的每个边缘都触及该单元格的边界。所以前导、尾随、顶部和底部的空格都是超级视图。没有什么可疑的约束。
  • @Jonathan:没错。请看我的回答。

标签: ios objective-c cocoa-touch uilabel


【解决方案1】:

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

附带说明:在解决布局问题时,我发现将临时背景颜色设置为各种亮色(​​例如,cell 设置为绿色,title 设置为蓝色)非常有用,因此可以清楚每个视图占用的帧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 2019-07-26
    • 2014-11-13
    • 2016-02-21
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多