uilabel视图不对齐

时间:2016-04-28 10:17:48

标签: ios objective-c xcode uitableview uilabel

我尝试过像

这样的事情
textLabel.textAlignment =NSTextAlignmentRight;

但是我的代码似乎没有任何效果。在cellforrawatindexpath内部

- (UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = (UITableViewCell *)[self.messageList dequeueReusableCellWithIdentifier:@"ChatListItem"];

    if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"OutGoing" owner:self options:nil];
        }
        cell = (UITableViewCell *)[nib objectAtIndex:0];
    }
    textLabel = (UILabel *)[cell viewWithTag:1];
            textLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"chat_b2.png"]];
            textLabel =[[UILabel alloc] initWithFrame:CGRectMake(21,12, 241,30)];
    NSString * test=[[rssOutputData objectAtIndex:indexPath.row]xml_msg];
    textLabel.text = test;
    textLabel.numberOfLines = 0;
    [textLabel sizeToFit];
    [cell addSubview:textLabel];
    return cell;
}

这是屏幕截图:App ScreenShot

在这里你可以看到(红色)文本左对齐我希望它对齐,请帮我解决这个问题。

4 个答案:

答案 0 :(得分:1)

使用[textLabel sizeToFit]标签框的大小会使文字适合其中,因此您的标签宽度将与文字相同,右对齐会将文字留在原位。评论这一行,它就可以了。

编辑:

[textLabel sizeToFit];
[textLabel setFrame:CGRectMake(21,12,241,textLabel.frame.size.height)];

答案 1 :(得分:0)

如果您使用sizetoFit,那么您的标签尺寸将根据内容大小减少。这不是对齐的问题。删除此行,然后添加textLabel.textAlignment =NSTextAlignmentRight;并检查它是否应该正常工作。

答案 2 :(得分:0)

您始终将textLabel框架设置为以下框架:

textLabel =[[UILabel alloc] initWithFrame:CGRectMake(21,12, 241,30)];

因此只有标签显示在左侧。尝试根据发送/接收消息更改标签帧。

希望有所帮助......

答案 3 :(得分:-1)

您的标签是您提供的框架的限制

textLabel =[[UILabel alloc] initWithFrame:CGRectMake(21,12, 241,30)];

所以它与您给出的框架对齐,即您的标签与特定宽度对齐,即30 ......您应该给出标签的宽度等于单元格的宽度和那么它会根据你的细胞对齐。