I'm trying to add a view to my tableview as a tableHeaderView. I drag a view from the interface builder and drop it into my tableview. The size of the header is a small, so I resize it by coding. When I run my app, it becomes like this:
If I change background colour to white colour
If I change background colour to clear idea
Here is the code I change my tableview header size:
self.myTableView.tableHeaderView?.frame = CGRectMake(0, 0, screenWidth, 290)
Any suggestion to fix it please!
Use this UItableView extension.
I was having the same issue
extension UITableView {
func setTableHeaderView(headerView: UIView?) {
// set the headerView
tableHeaderView = headerView
// check if the passed view is nil
guard let headerView = headerView else { return }
// check if the tableHeaderView superview view is nil just to avoid
// to use the force unwrapping later. In case it fail something really
// wrong happened
guard let tableHeaderViewSuperview = tableHeaderView?.superview else {
assertionFailure("This should not be reached!")
return
}
// force updated layout
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
// set tableHeaderView width
tableHeaderViewSuperview.addConstraint(headerView.widthAnchor.constraint(equalTo: tableHeaderViewSuperview.widthAnchor, multiplier: 1.0))
// set tableHeaderView height
let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
tableHeaderViewSuperview.addConstraint(headerView.heightAnchor.constraint(equalToConstant: height))
}
}
Create a xib which holds the kind of header view you want to add it on TableView. Then load your xib in viewWillAppear method of the controller using [[NSBundle mainBundle]loadNibNamed:#""] method. Now add that NSBundle returned view as tableView header by using, tv.tableHeaderView = <your UI view>;
Related
I am creating a dynamic height TableViewCell based on the contents of the Cell. I would like to create a custom separator between the cells. I have the following code in the TableViewCell swift file. It appears that the custom separator is created using the default height of the cell and not the calculated height of the cell based on the contents of the cell - which was calculated in the TableView heightForRowAt override function. As a result, the customer separator is rendered across the cell. It appears that the awakeFromNib is called before the height calculation. Any suggestions?
class FeedTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// add a custom seperator between table view cells.
let screenSize = UIScreen.main.bounds
let separatorHeight = CGFloat(10.0)
let additionalSeparator = UIView.init(frame: CGRect(x: 0, y: self.frame.size.height-separatorHeight, width: screenSize.width, height: separatorHeight))
additionalSeparator.backgroundColor = UIColor(named: "TEXTVIEWCELL_SEPARATOR")
self.addSubview(additionalSeparator)
}
}
The awakeFromNib is called before the height calculation. While the solution works for fixed height TableViewCells, it won't work for variable height TableViewCells. The solution that I used was to create a view on the bottom of the TableViewCell, use constraints to pin it to the bottom of the TableViewCell. You can size the view to 10pt and of course set the color. I did this in StoryBoards, not programmatically.
I'm working on profile screen, there is a UITableView inside the ViewController and I placed all user info inside the UITableView Header. To make screen more accurate due to different sizes of "About" label I use Autolayout with this code:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
sizeHeaderToFit()
}
func sizeHeaderToFit() {
let headerView = tableView.tableHeaderView!
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame
tableView.tableHeaderView = headerView
}
Everything works fine, but the last string of About label is not showing, text interrupts (I set word wrap):
Add a height constraint on tableview header and try to change height constraint where you are changing frame. As you are using autolayout so you should play with the constraints rather than playing directly with the frames
you can follow this tutorial
https://useyourloaf.com/blog/variable-height-table-view-header/
Hope it will help you.
func setTableHeader(){
let headerWidth = Double(tableHeader.frame.width)
// also tried let headerWidth = Double(tableView.frame.width)
print("header width is \(headerWidth)")
}
func viewWillAppear(){ output --> 351
setTableHeader()
//also tried in View Did Appear
}
func viewDidDisappear(){ output --> 296
setTableHeader()
}
The outputs refer to what occurs when run on Iphone SE. I designed my tableview and table header with constraints in Storyboard with the Iphone 6 display. I was able to get the result I wanted by changing setTableHeader to reflect view.frame.width - (left and right constraints from storyboard), however I was wondering why I couldnt get this to work, and what the less hacky work around would be? Also I am in actuality setting the dimensions of table header's subviews inside setTableHeader, but these subviews have no constraints (programatically nor in storyboard), in case that is relevant.
Thank you.
Try this , The solution was to override UIViewController().viewDidLayoutSubviews(), get the proper size of the header view based on it’s constraints, set the frame on the header, and reset it as the table header view
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Dynamic sizing for the header view
if let headerView = tableView.tableHeaderView {
let height = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
var headerFrame = headerView.frame
// If we don't have this check, viewDidLayoutSubviews() will get
// repeatedly, causing the app to hang.
if height != headerFrame.size.height {
headerFrame.size.height = height
headerView.frame = headerFrame
tableView.tableHeaderView = headerView
}
}
}
Please try to add this code to viewDidLayoutSubviews method.
All views got their actual sizes only alter layout. Method viewDidLayoutSubviews called before viewDidAppear and after viewWillAppear.
I have a scrollview that contain some element (uiimage, webview ,...)
in buttom of scrollview add tableview (comments list). Problem: although tableview is part of scrollview, but scrollview scroll separate and tableview scrolling separate!
I want at the end of scrollview and start tableview scrollview scrolling tableview and tableview scroll disabled.
I used it code:
Swift:
override func intrinsicContentSize() -> CGSize {
self.layoutIfNeeded()
return CGSizeMake(UIViewNoIntrinsicMetric, contentSize.height)
}
Objective C:
-(CGSize)intrinsicContentSize{
[self layoutIfNeeded];
return CGSizeMake(UIViewNoIntrinsicMetric, contentSize.height)}
but don't work.
thanks for help
That happens because it is the behavior of having a table view inside a scroll view. That should be happening.
Solution: Destroy the scrollView, and implement a tableView with a header view, wish that header view it will be the view with uiimage, webview etc... and the tableView it will be your comments. This is the best way of implementing what you want, that is if i understood right what you actually want.
Adding a header to a table view example:
self.tableView.tableHeaderView = topView // where top view is the view wish contains your uimage, buttons etc...
Avoid bounce of ScrollView when we scroll the tableview. I have added the below line of code.It worked for me.
self.scrollView.delegate = self
scrollView.contentSize = CGSize(width: self.view.frame.width, height: 500)
scrollView.showsVerticalScrollIndicator = true
scrollView.tag = 1
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.tag != 1 {
self.scrollView.bounces = false
}
}
Thanks
I am trying to show 2 UITableViewController's inside an horizontal UIScrollView. I am using AUtoLayout and Size Classes. My storyboards are of size Inferred. This is what I did for my test:
Add an UIScrollView and choose Update Constraints for AutoLayout from Resolve AutoLayout Issues.
Setup one UITableViewController and one UIViewController which inherits from UITableViewDelegate and UITableViewDataSource (I wanted to try both ways to use table views)
For both of them I added an UIButton on the right hand side and for AutoLayout I choose top and trailing edge to be fixed on the right.
After I run the code for UITableViewController I can only the "n" from Button if I click on the cell, I can see the button.
For the UIViewController table view I don't see the button at all.
Here is a print screen:
And here is my code for the scroll view controller:
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
let testTableVC = self.storyboard!.instantiateViewControllerWithIdentifier("TestTableViewController") as! TestTableViewController;
let testVC = self.storyboard!.instantiateViewControllerWithIdentifier("TestViewController") as! TestViewController;
var bounds = UIScreen.mainScreen().bounds
var width = bounds.size.width
var height = bounds.size.height;
scrollView!.contentSize = CGSizeMake(2*width, height);
let viewControllers = [testTableVC, testVC]
var idx:Int = 0;
for viewController in viewControllers {
// index is the index within the array
// participant is the real object contained in the array
addChildViewController(viewController);
let originX:CGFloat = CGFloat(idx) * width;
viewController.view.frame = CGRectMake(originX, 0, width, height);
scrollView!.addSubview(viewController.view)
viewController.didMoveToParentViewController(self)
idx++;
}
}
edit:
https://github.com/adrianstanciu24/scrollviewtest
I've created pull request that solves this. What was wrong is that you've used default UITableViewCell and added some custom content to it in storyboard. Table view then dequeued the default cell and drawn the default cell atop of the one from storyboard (with margins on sides - so only right part of your button was visible). You need to create custom UITableViewCell, connect outlets and dequeue the custom cell, the default one doesn't know anything about your button.