UITableViewAutomaticDimension이 작동하지 않는 이유는 무엇입니까?
안녕에 대한 동적 높이 응답 질문의 많음이 UITableViewCell의는 UITableView. 그러나 나는 그것을했을 때 그것이 이상하다는 것을 안다.
여기에 몇 가지 대답이 있습니다.
일반적으로 이것은 셀의 동적 높이에 응답합니다.
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
하지만 제 경우에는이 라인이 아무 일도하지 않을 것 같아요.
내 UITableView분할보기 내에서 탭 바를 클릭 한 후 표시됩니다. 도움이 되셨나요?
뭔가 빠졌 나봐요. 누구든지 내가 어리석은 일을하는 데 2 시간을 보냈습니다.
제목이 길 수 있지만 레이블은 그렇지 않습니다.

그리고 이것은 내 세포입니다

UITableViewAutomaticDimension이 작동하도록하려면 셀 컨테이너보기에 대한 모든 왼쪽, 오른쪽, 아래쪽 및 위쪽 제약 조건을 설정해야합니다. 귀하의 경우 제목 아래의 레이블에 대한 superview 제약 조건에 누락 된 하단 공간을 추가해야합니다
프로그래밍 방식으로 제약 조건을 추가했으며 실수로 contentView속성이 아닌 셀에 직접 추가했습니다 . 제약 사항을 추가하여 contentView해결했습니다!
행 높이 및 예상 행 높이에 대한 자동 치수를 설정하려면 다음 단계를 수행하여 셀 / 행 높이 레이아웃에 효과적인 자동 치수를 확인하십시오.
- tableview dataSource 및 위임 할당 및 구현
UITableViewAutomaticDimensionrowHeight 및 expectedRowHeight에 할당- 델리게이트 / dataSource 메서드 구현 (즉
heightForRowAt, 값UITableViewAutomaticDimension을 반환 )
-
목표 C :
// in ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@property IBOutlet UITableView * table;
@end
// in ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.table.dataSource = self;
self.table.delegate = self;
self.table.rowHeight = UITableViewAutomaticDimension;
self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
빠른:
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Don't forget to set dataSource and delegate for table
table.dataSource = self
table.delegate = self
// Set automatic dimensions for row height
// Swift 4.2 onwards
table.rowHeight = UITableView.automaticDimension
table.estimatedRowHeight = UITableView.automaticDimension
// Swift 4.1 and below
table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = UITableViewAutomaticDimension
}
// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Swift 4.2 onwards
return UITableView.automaticDimension
// Swift 4.1 and below
return UITableViewAutomaticDimension
}
UITableviewCell의 레이블 인스턴스
- 줄 수를 0으로 설정 (& 줄 바꿈 모드 = 꼬리 자르기)
- 수퍼 뷰 / 셀 컨테이너에 대한 모든 제약 (위, 아래, 오른쪽 왼쪽)을 설정합니다.
- 선택 사항 : 데이터가 없더라도 라벨로 덮는 최소 세로 영역을 원하는 경우 라벨의 최소 높이를 설정합니다.

참고 : 콘텐츠 크기에 따라 조정해야하는 동적 길이의 레이블 (UIElements)이 두 개 이상있는 경우 : 더 높은 우선 순위로 확장 / 압축하려는 레이블에 대해 '콘텐츠 포옹 및 압축 저항 우선 순위'를 조정합니다.
또한 셀의 UILabel에 대한 라인이 0으로 설정되어 있는지 확인하십시오. 1로 설정하면 수직으로 늘어나지 않습니다.
특정 사례가 있는데 내가 읽은 솔루션의 99 %가 작동하지 않았습니다. 나는 내 경험을 공유 할 것이라고 생각했다. 이 문제를 해결하기 전에 몇 시간 동안 고생했기 때문에 도움이 될 수 있기를 바랍니다.
내 시나리오 :
- 하나의 ViewController에서 두 개의 TableView를 사용하고 있습니다.
- 나는 사용자 정의 셀 (XIB를)로드 하는 tableviews에
- 셀의 동적 콘텐츠는 두 개의 레이블로 구성됩니다.
- 페이지는 ScrollView를 사용합니다.
내가 달성하기 위해 필요한 것 :
- 동적 TableView 높이
- 동적 TableViewCells 높이
원활하게 작동하기 위해 확인해야 할 사항 :
모든 튜토리얼과 답변이 말해 주듯이 라벨 / 콘텐츠 (상단, 하단, 선행 및 후행)에 대한 모든 제약 조건을 설정하고 ContentView (Superview)로 설정합니다. 이 비디오 자습서가 도움이 될 것 입니다.
viewWillAppear내 ViewController 의 메서드에서 내 tableViews 중 하나 (tableView2)에 예상 행 높이를 제공하고 다음과 같이 사용합니다UITableViewAutomaticDimension(모든 자습서 / 답변에서 볼 수 있음).override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView2.estimatedRowHeight = 80 tableView2.rowHeight = UITableViewAutomaticDimension }
저에게는 이러한 이전 단계가 충분하지 않았습니다. 내 TableView는 간단히 predictRowHeight를 가져 와서 셀 수를 곱합니다. Meeeh.
나는 두 개의 서로 다른 tableViews를 사용하고, 나는 그들 각각에 대한 출구를 만들어
tableView1와tableView2.viewDidLayoutSubviews메서드 에서 크기를 조정할 수 있습니다 . 내가 어떻게했는지 의견으로 자유롭게 물어보십시오.One additional step fixed it for me, by adding this to the
viewDidAppearmethod:override func viewDidAppear(_ animated: Bool) { tableView1.reloadData() // reloading data for the first tableView serves another purpose, not exactly related to this question. tableView2.setNeedsLayout() tableView2.layoutIfNeeded() tableView2.reloadData() }
Hope that helps someone!
As of iOS 11 and Xcode 9.3, most of the above information is wrong. Apple's Guide suggests setting
tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableViewAutomaticDimension
WWDC 2017 session 245 (Building Apps with Dynamic Type, about 16:33 into the video) suggests something similar. None of this made a difference for me.
For a Subtitle style cell, all that's necessary to get self-sizing table view cells is to set the number of lines (in the Label section of the attributes inspector) to 0 for both the Title and Subtitle. If one of these labels is too long and you don't set the number of lines to 0, the table view cell won't adjust its size.
Forgot to remove tableView(heightForRowAt:indexPath:)
It could be the case that, like me, you accidentally forgot to remove the boilerplate code for the heightForRowAt method.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60.0
}
In my case i had two UITableViews, i had to modify this method as
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGFloat height = 0.0;
if (tableView == self.tableviewComments) {
return UITableViewAutomaticDimension;
}else if (tableView == self.tableViewFriends) {
height = 44.0;
}
return height;
}
Try this, Simple solution it's work for me,
In viewDidLoad write this code,
-(void)viewDidLoad
{
[super viewDidLoad];
self.tableView.estimatedRowHeight = 100.0; // for example. Set your average height
self.tableView.rowHeight = UITableViewAutomaticDimension;
}
In cellForRowAtIndexPath write this code,
-(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.numberOfLines = 0; // Set label number of line to 0
cell.textLabel.text=[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"menu"];
[cell.textLabel sizeToFit]; //set size to fit
return cell;
}
For anyone that maybe faced the same problem with me: I struggled for an hour to make it work. A simple UIlabel with top, bottom left and right constraints. I used the willDisplayCell to pass the data to the cell and this was causing problems in cells height. As long as I put that code in cellForRow everything worked just fine. Didn't understand why this happened, maybe the cell height was calculated before willDisplayCell was called so there was no content to make the right calculation. I was just wanted to mention and probably help someone with the same problem.
it was working for me fine in iOS 11 and above, while breaking in iOS 10 the solution was to add
table.rowHeight = UITableView.automaticDimension
table.estimatedRowHeight = 200 // a number and not UITableView.automaticDimension
also make sure you add "heightForRowAt" even if it works in iOS 11 and above, its needed if you support iOS 10
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
For my setup, I first double checked the constraints in the Storyboard for the UITableViewCell were unambiguous top to bottom, and then had to modify code in 2 places.
UITableViewDelegate'stableView(_:heightForRowAt:)func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension // return UITableViewAutomaticDimension for older than Swift 4.2 }UITableViewDelegate'stableView(_:estimatedHeightForRowAt:)func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension // return UITableViewAutomaticDimension for older than Swift 4.2 }
Step 1 and 2, lets you to apply autosizing just for particular rows. For applying to the whole UITableView, use:
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = UITableView.automaticDimension
// return UITableViewAutomaticDimension for older than Swift 4.2
In order to make UITableViewAutomaticDimension to work, you need to make sure all 4 corners' constraints is added to the superview. In most case, it works well with UILabel, but sometimes i find UITextView does the trick when UILabel not working well at the time. So try to switch to UITextView and make sure Scrolling Enabled is unchecked in storyboard, or you can also set it programmatically.
I had three horizontal items and the most left had a constraint to left, middle one had top, bottom, to the left item and to the right item. The right one had a right, and left to the middle item. The solution was to add additional left and right constraints to the middle item (my label) that were >= some number to the cell.
Make sure all views in the cell are constrained to the Content View and not to the cell.
As apple says:
lay out the table view cell’s content within the cell’s content view. To define the cell’s height, you need an unbroken chain of constraints and views (with defined heights) to fill the area between the content view’s top edge and its bottom edge.
I've got a new solution..that's worked for me.
basically UITableViewAutomaticDimension renamed as UITableView.automaticDimension... I hope..it wo
참고 URL : https://stackoverflow.com/questions/30299319/why-uitableviewautomaticdimension-not-working
'IT TIP' 카테고리의 다른 글
| 위치 서비스가 활성화되어 있는지 확인 (0) | 2020.11.02 |
|---|---|
| CSS 위치 절대 전체 너비 문제 (0) | 2020.11.02 |
| HH : MM : SS 형식의 두 시간 문자열을 어떻게 비교할 수 있습니까? (0) | 2020.11.02 |
| 상황에 맞는 메뉴로 Bootstrap 3 드롭 다운 메뉴 사용 (0) | 2020.11.02 |
| CSS에서 텍스트의 마지막 줄을 중앙 정렬하는 방법은 무엇입니까? (0) | 2020.11.02 |