【发布时间】: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