codememo

커스텀 셀 없이 UITableViewCell로 텍스트를 줄바꿈하는 방법

tipmemo 2023. 4. 18. 22:48
반응형

커스텀 셀 없이 UITableViewCell로 텍스트를 줄바꿈하는 방법

이것은 iPhone 0S 2.0 입니다.2.1에 대한 답변도 괜찮지만, 표에 대한 차이는 잘 모릅니다.

커스텀 셀을 작성하지 않고 텍스트를 줄바꿈할 수 있을 것 같습니다.UITableViewCell를 포함합니다.UILabel디폴트입니다.커스텀 셀을 작성하면 동작할 수 있다는 것은 알고 있습니다만, 이것은 제가 목표로 하고 있는 것이 아닙니다.현재의 어프로치가 기능하지 않는 이유를 알고 싶습니다.

라벨은 온 디맨드로 작성됩니다(셀이 텍스트 및 이미지 액세스를 지원하므로 필요할 때까지 데이터 뷰를 작성하지 않습니다).이러한 작업을 실시하면, 다음과 같은 일이 발생합니다.

cell.text = @""; // create the label
UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0];

그러면 유효한 라벨을 얻을 수 있지만numberOfLines(및 lineBreakMode)는 동작하지 않습니다.아직도 한 줄의 텍스트가 표시됩니다.에는 많은 높이가 있다.UILabel표시할 텍스트 - 높이 값을 반환하는 중입니다.heightForRowAtIndexPath.

보다 간단한 방법은 다음과 같습니다.

사용자 내부cellForRowAtIndexPath:기능.셀을 처음 작성할 때:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}

라벨의 행수가 0으로 설정되어 있는 것을 알 수 있습니다.따라서 필요한 만큼 회선을 사용할 수 있습니다.

다음 파트는 이 시스템의 크기를 지정하는 것입니다.UITableViewCell그렇게 될 거야, 그러니 네 옷에서 그렇게 해heightForRowAtIndexPath기능:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

    return labelSize.height + 20;
}

텍스트 주위에 버퍼가 조금 있는 것을 좋아하기 때문에 반환된 셀 높이에 20을 추가했습니다.

iOS7에 대한 팀 루피의 답변 업데이트:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];

    NSAttributedString *attributedText =
        [[NSAttributedString alloc]
            initWithString:cellText
            attributes:@
            {
                NSFontAttributeName: cellFont
            }];
    CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(tableView.bounds.size.width, CGFLOAT_MAX)
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    return rect.size.height + 20;
}

같은 문제를 겪었을 때의 경험을 기록하기 위한 간단한 코멘트/답변.코드 예제를 사용했음에도 불구하고 테이블 뷰 셀 높이는 조정되고 있었지만 셀 내부의 라벨은 여전히 올바르게 조정되지 않았습니다. 해결책은 셀 높이를 조정한 후에 발생하는 커스텀 NIB 파일에서 셀을 로드하는 것이었습니다.

또한 NIB 파일 내에 텍스트를 줄바꿈하지 않도록 설정했고 라벨에 사용할 행은 1개뿐이었습니다.NIB 파일 설정은 코드 내에서 조정한 설정보다 우선합니다.

제가 배운 교훈은 각 시점에서의 오브젝트 상태를 항상 염두에 두는 것이었습니다.아직 만들어지지 않았을지도 모릅니다.다른 사람을 죽인다.

텍스트만 추가할 경우UITableView셀, 2명의 대표자만 함께 작업하면 됩니다(추가 필요 없음).UILabels)

1)cellForRowAtIndexPath

2)heightForRowAtIndexPath

이 솔루션은 저에게 효과가 있었습니다.-

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:16];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;

    [cell setSelectionStyle:UITableViewCellSelectionStyleGray]; 
    cell.textLabel.text = [mutArr objectAtIndex:indexPath.section];
    NSLog(@"%@",cell.textLabel.text);

    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png" ]];

    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{  
    CGSize labelSize = CGSizeMake(200.0, 20.0);

    NSString *strTemp = [mutArr objectAtIndex:indexPath.section];

    if ([strTemp length] > 0)
        labelSize = [strTemp sizeWithFont: [UIFont boldSystemFontOfSize: 14.0] constrainedToSize: CGSizeMake(labelSize.width, 1000) lineBreakMode: UILineBreakModeWordWrap];

    return (labelSize.height + 10);
}

은 " " " 입니다.mutArr이치노

편집:- 여기 제가 찍은 어레이가 있습니다.

mutArr= [[NSMutableArray alloc] init];

[mutArr addObject:@"HEMAN"];
[mutArr addObject:@"SUPERMAN"];
[mutArr addObject:@"Is SUPERMAN powerful than HEMAN"];
[mutArr addObject:@"Well, if HEMAN is weaker than SUPERMAN, both are friends and we will never get to know who is more powerful than whom because they will never have a fight among them"];
[mutArr addObject:@"Where are BATMAN and SPIDERMAN"];

이제 테이블 뷰에 셀프사이징 셀을 사용할 수 있습니다.다음과 같이 테이블 보기를 설정합니다.

tableView.estimatedRowHeight = 85.0 //use an appropriate estimate tableView.rowHeight = UITableViewAutomaticDimension

Apple 레퍼런스

저는 다음과 같은 솔루션을 사용합니다.

데이터는 멤버별로 제공됩니다.

-(NSString *)getHeaderData:(int)theSection {
    ...
    return rowText;
}

할 수 .cellForRowAtIndexPath셀을 정의하거나 글꼴을 정의하고 이러한 값을 "셀"에 할당합니다.에 주의:numberoflines을 가져간다는 의 '으로 되어 있습니다

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

    UIFont *cellFont = [UIFont fontWithName:@"Verdana" size:12.0];
    cell.textLabel.text= [self getRowData:indexPath.section];
    cell.textLabel.font = cellFont;
    cell.textLabel.numberOfLines=0;
    return cell;
}

»heightForRowAtIndexPath, 나는 포장된 텍스트의 높이를 계산합니다.신호 크기는 셀 폭과 관련이 있어야 합니다.아이패드 1024입니다.iPhone en iPod 320 † 。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIFont *cellFont = [UIFont fontWithName:@"Verdana" size:12.0];
    CGSize boundingSize = CGSizeMake(1024, CGFLOAT_MAX);
    CGSize requiredSize = [[self getRowData:indexPath.section] sizeWithFont:cellFont constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
    return requiredSize.height;    
}

이것은 매우 심플하고 간단하다는 것을 알았습니다.

[self.tableView setRowHeight:whatEvereight.0f];

예:

[self.tableView setRowHeight:80.0f];

이것이 최선의/표준적인 접근방식이 될 수도 있고 아닐 수도 있지만, 제 경우에는 효과가 있었습니다.

내 코드를 빠르게 시도해봐.이 코드는 일반 UILabel에서도 작동합니다.

extension UILabel {
    func lblFunction() {
        //You can pass here all UILabel properties like Font, colour etc....
        numberOfLines = 0
        lineBreakMode = .byWordWrapping//If you want word wraping
        lineBreakMode = .byCharWrapping//If you want character wraping
    }
}

이렇게 간단하게 전화하세요.

cell.textLabel.lblFunction()//Replace your label name 

나는 이것이 더 좋고 짧은 해결책이라고 생각한다.만 정해 .UILabel )textLabelsizeToFit모든 게 잘 될 거야

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

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

    // Configure the cell...
    cell.textLabel.text = @"Whatever text you want to put here is ok";
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    [cell.textLabel sizeToFit];

    return cell;
}

를 할 수 없다고 UITableViewCell'sUILabel이 일을 하기 위해서.요.UILabel하여 사용하세요.numberOfLinessizeToFit을 사용하다예를 들어 다음과 같습니다.

UILabel* label = [[UILabel alloc] initWithFrame:cell.frame];
label.numberOfLines = <...an appriate number of lines...>
label.text = <...your text...>
[label sizeToFit];
[cell addSubview:label];
[label release];

언급URL : https://stackoverflow.com/questions/129502/how-do-i-wrap-text-in-a-uitableviewcell-without-a-custom-cell

반응형