어떻게 포장 텍스트에 UITableViewCell 지 않고 사용자 지정 셀
-
02-07-2019 - |
문제
이에 아이폰 0S2.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에 대한 Tim Rupe의 답변을 업데이트했습니다.
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 파일 발생하는 후에 셀의 높이를 조정됩니다.
나는 나의 설정 내부의 펜촉 파일을 포장하지 않는 텍스트,그리고만 있는 1 라인에 대한 라벨;펜촉 파일의 설정을 무시하는 설정을 조정 내부의 코드입니다.
의 교훈이었는지 확인을 항상 마음에 무슨 상태의 개체는 각 지점에서 시간 그들이 만들어지지 않았을 수 있습니다!...hth 사람입니다.
텍스트 만 추가 해야하는 경우 UITableView
셀, 우리는 두 대의 대의원 만 필요합니다 (추가 추가 필요 없음 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"];
이제 TableViews에는 자체 크기의 셀이있을 수 있습니다. 테이블보기를 다음과 같이 설정하십시오
tableView.estimatedRowHeight = 85.0 //use an appropriate estimate
tableView.rowHeight = UITableViewAutomaticDimension
다음 솔루션을 사용합니다.
데이터는 멤버에서 별도로 제공됩니다.
-(NSString *)getHeaderData:(int)theSection {
...
return rowText;
}
취급은 쉽게 수행 할 수 있습니다 cellForRowAtIndexPath
. 셀을 정의 / 글꼴을 정의하고 이러한 값을 결과 "셀"에 할당하십시오. 주목하십시오 numberoflines
"0"으로 설정되며, 이는 필요한 것을 가져갑니다.
- (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
, 랩핑 된 텍스트의 높이를 계산합니다. 신체 크기는 셀의 너비와 관련이 있어야합니다. iPad의 경우 이것은 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];
이것은 최선의 / 표준 접근법 일 수도 있고 아닐 수도 있지만, 제 경우에는 효과가있었습니다.
Swift에서 내 코드를 사용해보십시오. 이 코드는 정상적인 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
(textLabel
) 셀의)는 지정하여 높이에 대해 자동 계산합니다. sizeToFit
그리고 모든 것이 괜찮을 것입니다.
- (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's
사적인 UILabel
이것을하기 위해. 새로운 것을 추가 할 수 있습니다 UILabel
세포에 직접 사용하십시오 numberOfLines
~와 함께 sizeToFit
적절하게 크기를 조정합니다. 같은 것 :
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];