Programming

UITableView의 tableHeaderView 크기를 조정하는 방법은 무엇입니까?

procodes 2020. 8. 18. 19:28
반응형

UITableView의 tableHeaderView 크기를 조정하는 방법은 무엇입니까?


tableHeaderView 크기를 조정하는 데 문제가 있습니다. 간단하지 않습니다.

1) UITableView 및 UIView (100 x 320 px)를 만듭니다.

2) UIView를 UITableView의 tableHeaderView로 설정하십시오.

3) 빌드 앤 고. 모든 것이 괜찮습니다.

이제 tableHeaderView의 크기를 조정하고 싶으므로 viewDidLoad에이 코드를 추가합니다.

self.tableView.autoresizesSubviews = YES;

self.tableView.tableHeaderView = myHeaderView;
self.tableView.tableFooterView = myFooterView;

CGRect newFrame = self.tableView.tableHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
self.tableView.tableHeaderView.frame = newFrame;

tableHeaderView의 높이는 200으로 나타나야하지만 100으로 나타납니다.

내가 쓰면 :

self.tableView.autoresizesSubviews = YES;


CGRect newFrame = myHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
myHeaderView.frame = newFrame;


self.tableView.tableHeaderView = myHeaderView;
self.tableView.tableFooterView = myFooterView;

그런 다음 내가 원하는대로 200의 높이로 시작합니다. 하지만 런타임에 수정할 수 있기를 원합니다.

나는 또한 이것을 시도했지만 성공하지 못했습니다.

self.tableView.autoresizesSubviews = YES;

self.tableView.tableHeaderView = myHeaderView;
self.tableView.tableFooterView = myFooterView;

CGRect newFrame = self.tableView.tableHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
self.tableView.tableHeaderView.frame = newFrame;

[self.tableView.tableHeaderView setNeedsLayout];
[self.tableView.tableHeaderView setNeedsDisplay];
[self.tableView setNeedsLayout];
[self.tableView setNeedsDisplay];

여기서 요점은 : 런타임에서 tableHeaderView의 크기를 어떻게 조정합니까 ??

누구든지 이것을 할 수 있습니까?

감사

iMe


참고 : tableHeaderView를 수정하고 다시 설정하여 작동하도록했습니다. 이 경우 UIWebView 하위 뷰가로드를 마쳤을 때 tableHeaderView의 크기를 조정하고 있습니다.

[webView sizeToFit];
CGRect newFrame = headerView.frame;
newFrame.size.height = newFrame.size.height + webView.frame.size.height;
headerView.frame = newFrame;
[self.tableView setTableHeaderView:headerView];

이 답변은 오래되었으며 iOS 7 이상에서는 작동하지 않는 것 같습니다.

나는 같은 문제에 부딪 혔고 또한 변경 사항을 애니메이션화하기를 원했기 때문에 헤더 뷰에 대한 UIView의 하위 클래스를 만들고 다음 메서드를 추가했습니다.

- (void)adjustTableHeaderHeight:(NSUInteger)newHeight{
    NSUInteger oldHeight = self.frame.size.height;
    NSInteger originChange = oldHeight - newHeight;

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:1.0f];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

    self.frame = CGRectMake(self.frame.origin.x, 
                        self.frame.origin.y, 
                        self.frame.size.width, 
                        newHeight);

    for (UIView *view in [(UITableView *)self.superview subviews]) {
        if ([view isKindOfClass:[self class]]) {
            continue;
        }
        view.frame = CGRectMake(view.frame.origin.x, 
                            view.frame.origin.y - originChange, 
                            view.frame.size.width, 
                            view.frame.size.height);
    }

    [UIView commitAnimations];
}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
    [(UITableView *)self.superview setTableHeaderView:self];
}

이것은 본질적으로 호출 클래스와 동일한 클래스 유형이 아닌 UITableView의 모든 하위 뷰에 애니메이션을 적용합니다. 애니메이션이 끝날 때 수퍼 뷰 (UITableView)에서 setTableHeaderView를 호출합니다. 이렇게하지 않으면 UITableView 내용이 다음에 사용자가 스크롤 할 때 뒤로 건너 뜁니다. 지금까지 내가 찾은 유일한 제한은 애니메이션이 진행되는 동안 사용자가 UITableView를 스크롤하려고하면 머리글보기의 크기가 조정되지 않은 것처럼 스크롤이 애니메이션됩니다 (애니메이션이 빨리).


변경 사항을 조건부로 애니메이션하려면 다음을 수행 할 수 있습니다.

- (void) showHeader:(BOOL)show animated:(BOOL)animated{

    CGRect closedFrame = CGRectMake(0, 0, self.view.frame.size.width, 0);
    CGRect newFrame = show?self.initialFrame:closedFrame;

    if(animated){
        // The UIView animation block handles the animation of our header view
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        // beginUpdates and endUpdates trigger the animation of our cells
        [self.tableView beginUpdates];
    }

    self.headerView.frame = newFrame;
    [self.tableView setTableHeaderView:self.headerView];

    if(animated){
        [self.tableView endUpdates];
        [UIView commitAnimations];
    }
}

애니메이션은 두 개로 접혀 있습니다.

  1. 아래에있는 셀의 애니메이션 tableHeaderView. 이것은 beginUpdates사용하여 수행됩니다.endUpdates
  2. 실제 헤더보기의 애니메이션입니다. 이것은 UIView애니메이션 블록을 사용하여 수행됩니다 .

이 두 애니메이션을 동기화하려면을 animationCurve로 설정 UIViewAnimationCurveEaseInOut하고 기간을 로 설정해야 합니다 0.3. 이는 UITableView가 애니메이션에 사용하는 것 같습니다.

최신 정보

나는 이것을하는 gihub에 Xcode 프로젝트를 만들었다. besi / ios-quickiesResizeTableHeaderViewAnimated 에서 프로젝트 확인

스크린 샷


myHeaderView의 높이를 다음과 같이 설정하면 작동해야한다고 생각합니다.

CGRect newFrame = myHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
myHeaderView.frame = newFrame;

self.tableView.tableHeaderView = myHeaderView;

iOS 7까지 위의 @garrettmoon 솔루션을 사용했습니다.
다음은 @garrettmoon을 기반으로 한 업데이트 된 솔루션입니다.

- (void)adjustTableHeaderHeight:(NSUInteger)newHeight animated:(BOOL)animated {

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:[CATransaction animationDuration]];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

    self.frame = CGRectMake(self.frame.origin.x,
                        self.frame.origin.y,
                        self.frame.size.width,
                        newHeight);

    [(UITableView *)self.superview setTableHeaderView:self];

    [UIView commitAnimations];
}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
    [(UITableView *)self.superview setTableHeaderView:self];
}

이것은 iOS 7 및 8에서 저에게 효과적이었습니다.이 코드는 테이블 뷰 컨트롤러에서 실행 중입니다.

[UIView animateWithDuration:0.3 animations:^{
    CGRect oldFrame = self.headerView.frame;
    self.headerView.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, oldFrame.size.width, newHeight);
    [self.tableView setTableHeaderView:self.headerView];
}];

tableHeaderView의 setter 때문입니다.

tableHeaderView를 설정하기 전에 UIView 높이를 설정해야합니다. (애플이이 프레임 워크를 오픈 소스한다면 훨씬 쉬울 것입니다 ...)


iOS 9 이하에서는 tableHeaderView크기를 조정 한 후 다시 레이아웃하지 않습니다. 이 문제는 iOS 10에서 해결되었습니다.

이 문제를 해결하려면 다음 코드를 사용하십시오.

self.tableView.tableHeaderView = self.tableView.tableHeaderView;

iOS 9.x에서는이 viewDidLoad작업을 잘 수행 합니다.

var frame = headerView.frame
frame.size.height = 11  // New size
headerView.frame = frame

headerView@IBOutlet var headerView: UIView!tableHeaderView로 작동하기 위해 tableView의 맨 위에 배치되는 스토리 보드에서 로 선언 되고 연결됩니다.


설정 높이 헤더보기 속성 tableView.tableHeaderView에있는 것은 viewDidLoad예상대로되지 작업을 보인다 헤더보기 높이가 아직 변경되지.

많은 시도를 위해이 문제에 맞서 싸운 후. - (void)didMoveToParentViewController:(UIViewController *)parent메서드 내에서 헤더 뷰 생성 로직을 호출하여 높이를 변경할 수 있음을 발견했습니다 .

따라서 예제 코드는 다음과 같습니다.

- (void)didMoveToParentViewController:(UIViewController *)parent {
    [super didMoveToParentViewController:parent];

    if ( _tableView.tableHeaderView == nil ) {
        UIView *header = [[[UINib nibWithNibName:@"your header view" bundle:nil] instantiateWithOwner:self options:nil] firstObject];

        header.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), HeaderViewHeight);

        [_tableView setTableHeaderView:header];
    }
}

이는 자동 레이아웃을 사용 translatesAutoresizingMaskIntoConstraints = false하고 사용자 정의 헤더보기로 설정된 경우에만 해당됩니다 .

가장 좋고 가장 간단한 방법은 intrinsicContentSize. 내부적 으로 머리글 / 바닥 글 크기를 결정하는 UITableView데 사용 intrinsicContentSize됩니다. intrinsicContentSize사용자 정의보기에서 재정의 한 후 수행해야하는 작업은 다음과 같습니다.

  1. 사용자 지정 머리글 / 바닥 글보기의 레이아웃 (하위보기) 구성
  2. 호출 invalidateIntrinsicContentSize()
  3. 호출 tableView.setNeedsLayout()하고tableView.layoutIfNeeded()

그러면 UITableView의 머리글 / 바닥 글이 원하는대로 업데이트됩니다. 보기를 nil로 설정하거나 재설정 할 필요가 없습니다.

One thing really interesting for the UITableView.tableHeaderView or .tableFooterView is that UIStackView loose its ability to manage its arrangedSubviews. If you want to use UIStackView as a tableHeaderView or tableFooterView, you have to embed the stackView in a UIView and override UIView's intrinsicContentSize.


I found the initWithFrame initializer of a UIView doesn't properly honor the rect I pass in. Hence, I did the following which worked perfectly:

 - (id)initWithFrame:(CGRect)aRect {

    CGRect frame = [[UIScreen mainScreen] applicationFrame];

    if ((self = [super initWithFrame:CGRectZero])) {

        // Ugly initialization behavior - initWithFrame will not properly honor the frame we pass
        self.frame = CGRectMake(0, 0, frame.size.width, 200);

        // ...
    }
}

The advantage of this is it is better encapsulated into your view code.


I have implemented animated height change of the table's header to expand to overall screen when tapped. However, the code can help in other cases:

// Swift
@IBAction func tapped(sender: UITapGestureRecognizer) {

    self.tableView.beginUpdates()       // Required to update cells. 

    // Collapse table header to original height
    if isHeaderExpandedToFullScreen {   

        UIView.animateWithDuration(0.5, animations: { () -> Void in
            self.scrollView.frame.size.height = 110   // original height in my case is 110
        })

    }
    // Expand table header to overall screen            
    else {      
        let screenSize = self.view.frame           // "screen" size

        UIView.animateWithDuration(0.5, animations: { () -> Void in
            self.scrollView.frame.size.height = screenSize.height
        })
    }

    self.tableView.endUpdates()  // Required to update cells. 

    isHeaderExpandedToFullScreen= !isHeaderExpandedToFullScreen  // Toggle
}

UITableView resizing header - UISearchBar with Scope Bar

I wanted a UITableView with a UISearchBar as the header to the table so I have a hierarchy that looks like this

UITableView
  |
  |--> UIView
  |     |--> UISearchBar
  |
  |--> UITableViewCells

UISearchBarDelegate methods

As has been stated elsewhere, if you don't setTableViewHeader after changing it, nothing will happen.

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsScopeBar = YES;
    [UIView animateWithDuration:0.2f animations:^{
        [searchBar sizeToFit];
        CGFloat height = CGRectGetHeight(searchBar.frame);

        CGRect frame = self.tableView.tableHeaderView.frame;
        frame.size.height = height;
        self.tableHeaderView.frame = frame;
        self.tableView.tableHeaderView = self.tableHeaderView;
    }];

    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    searchBar.showsScopeBar = NO;
    [UIView animateWithDuration:0.f animations:^{
        [searchBar sizeToFit];

        CGFloat height = CGRectGetHeight(searchBar.frame);

        CGRect frame = self.tableView.tableHeaderView.frame;
        frame.size.height = height;
        self.tableHeaderView.frame = frame;
        self.tableView.tableHeaderView = self.tableHeaderView;
    }];

    [searchBar setShowsCancelButton:NO animated:YES];
    return YES;
}

If custom headerView is designed using autolayout and headerView needs to be updated after web-fetch or similar lazy task. then in iOS-Swift I did this and got my headerView updated using bellow code:

//to reload your cell data
self.tableView.reloadData()
dispatch_async(dispatch_get_main_queue(),{
// this is needed to update a specific tableview's headerview layout on main queue otherwise it's won't update perfectly cause reloaddata() is called
  self.tableView.beginUpdates()
  self.tableView.endUpdates()
} 

Obviously, by now Apple should have implemented UITableViewAutomaticDimension for tableHeaderView & tableFooterView...

The following seems to work for me using layout contraint(s):

CGSize   s  = [ self  systemLayoutSizeFittingSize : UILayoutFittingCompressedSize ];
CGRect   f  = [ self  frame ];

f.size   = s;

[ self  setFrame : f ];

If your tableHeaderView is a content adjustable webView,you can try:

[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    self.webView.height = self.webView.scrollView.contentSize.height;
    self.tableView.tableHeaderView = self.webView;
}

I tested it on iOS9 and iOS11,worked well.


Did you try [self.tableView reloadData] after changing the height?

참고URL : https://stackoverflow.com/questions/341256/how-to-resize-a-tableheaderview-of-a-uitableview

반응형