iOS - UITableViewCell文本对齐

Mil*_*lad 5 text-alignment uitableview ios

我添加了一个tableView并将一个表格视图单元格拖入其中.在实用工具面板中,我将样式更改为副标题.我也尝试在代码中更改它:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    cell.textLabel.textAlignment = UITextAlignmentCenter;
    cell.detailTextLabel.textAlignment = UITextAlignmentCenter;

    cell.textLabel.text = [myArray objectAtIndex:indexPath.row];
    cell.detailTextLabel.text = [myArray2 objectAtIndex:indexPath.row];

    return cell;
Run Code Online (Sandbox Code Playgroud)

中心对齐不起作用!

我已经尝试向单元格添加标签对象以获得解决方法.但我不知道如何访问它.即使我为它指定了一个插座,这也行不通:

cell.labelForCell....
Run Code Online (Sandbox Code Playgroud)

我该怎么办?有关如何使其按常规方式工作的任何建议,而无需在单元格中添加标签或其他内容?

Oma*_*ith 18

对于UITableViewCellStyleSubtitle文本对齐无法更改您将必须放置一个标签并添加对齐,为此,您可以使用此代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UILabel *myLabel;
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

        myLabel = [[UILabel alloc] initWithFrame:Your_Frame];
        //Add a tag to it in order to find it later
        myLabel.tag = 111;
        //Align it
        myLabel.textAlignment= UITextAlignmentCenter;

        [cell.contentView addSubview:myLabel];
    }

    myLabel = (UILabel*)[cell.contentView viewWithTag:111];
    //Add text to it
    myLabel.text = [myArray objectAtIndex:indexPath.row];

    return cell;
}
Run Code Online (Sandbox Code Playgroud)