简体   繁体   中英

UIView with labels at top of UITableviewcontroller Swift

I am trying to keep a UIView with a label, segmentedControl and a button at the top of my UITableViewController as it scrolls. I cannot use a ViewController with UITableView because my TableViewCells are static with UITextFields in them. I know this can be done via ViewController and ContainerViewController, however, this makes things complicated with the amount of data that needs to get passed between the views. I am looking for a scrollViewDidScroll solution in swift.

Here is what I have so far. I have the View already created in storyboards (maybe that is part of the problem.) labelView is connected via outlet.

    override func scrollViewDidScroll(scrollView: UIScrollView) {
    var rect = self.labelView.frame
    rect.origin.y = min(0,scrollView.contentOffset.y + scrollView.contentInset.top);
    self.labelView.frame = rect;
}

If you have just one section then you may try adding the view in section header. yeah you have to change lot of thing but it will 100% work

I figured it out.

First I put a dummy blank view where I wanted my view to be. I did this otherwise it sets itself on top the tableview. I am sure you could also off set in code but this seemed easier. Then I created a separate view outside of the tableViewController with my labels and button set up. Connected this view via outlet. Here is the code to add the view and then keep its position when scrolling.

@IBOutlet var labelView: UIView!

override func viewDidLayoutSubviews() {
    self.view.addSubview(labelView)
    labelView.frame.size.width = self.view.frame.size.width
}

override func scrollViewDidScroll(scrollView: UIScrollView) {
    var rect = self.labelView.frame
    rect.origin.y = max(0,scrollView.contentOffset.y + scrollView.contentInset.top)
    self.labelView.frame = rect
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM