autolayout with dynamics subviews - ios

I am trying to make home screen on my ios 10 app like on photo from above. Green view is actually scroll view and i set constraints for it to cover whole View. Everything on scrollView i want to make scrollable. Yellow part is collection view with prototype cell. Number of items on this view is 6. Cell consists of photo and title. Table view is list of news (photo + title). When start app in table view I load 10 last news and rest of the news I getting with "load more" mechanism. I need proper work of app even on landscape orientation. I have problem to define this layout because collection view and tableView have dynamic height and space between them must be fixed. Usually on almost all tutorials people just fixed scrollView and GridView and in that case app looks good on portrait orientation but i need a more flexibility. Is it possible to achieve this through auto layout and constraints and if yes what are correct directions
UPDATE:
Content view
Collection view
What I want to achieve is to make collection view as a two columns and 3 rows in portrait orientation and 3 columns and 2 rows on landscape. Currently I have collectionView with a scroll but I want to be expanded al the time because content of collectionView should consists of 6 highlighted news.
On viewDidLoad I tried to set table view on correct position (after collection view):
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
collection.dataSource = self
collection.delegate = self
tableView.delegate = self
tableView.dataSource = self
self.view.addConstraint(
NSLayoutConstraint(
item: tableView,
attribute: .top,
relatedBy: .equal,
toItem: collection,
attribute: .bottom,
multiplier: 1.0,
constant: 20
))
tableView.frame = CGRect(x: 0,y: collection.collectionViewLayout.collectionViewContentSize.height,width: tableView.frame.width,height: tableView.frame.width ); // set new position exactly
downloadArticles(offset: "0") {}
}
An example of what I want to achieve is:
Currently I have this:

I think I got it working like this:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UICollectionViewDelegateFlowLayout, UITableViewDelegate {
#IBOutlet var collectionView: UICollectionView!
#IBOutlet var tableView: UITableView!
#IBOutlet var collectionViewHeightConstraint: NSLayoutConstraint!
#IBOutlet var tableViewHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "gridCell")
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "listCell")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// shrink wrap the collectionView and tableView to fit their content height snuggly
self.collectionViewHeightConstraint.constant = self.collectionView.contentSize.height
self.tableViewHeightConstraint.constant = self.tableView.contentSize.height
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - CollectionView Methods -
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
cell.backgroundColor = UIColor.lightGray
}
func calculateGridCellSize() -> CGSize {
// -----------------------------------------------------
// Calculate the size of the grid cells
// -----------------------------------------------------
let screenWidth = self.view.frame.size.width
let screenHeight = self.view.frame.size.height
var width:CGFloat = 0
var height:CGFloat = 0
if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation)) {
width = screenWidth / 2.0 - 0.5
height = width
}
else {
width = screenWidth / 3.0 - 1.0
height = screenHeight / 2.0 - 0.5
}
let size:CGSize = CGSize(width: width, height: height)
return size
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.calculateGridCellSize()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { (context) in
print("New screen size = \(size.width) x \(size.height)")
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionViewHeightConstraint.constant = self.collectionView.contentSize.height
self.tableViewHeightConstraint.constant = self.tableView.contentSize.height
self.view.layoutIfNeeded()
}) { (context) in
self.collectionViewHeightConstraint.constant = self.collectionView.contentSize.height
self.tableViewHeightConstraint.constant = self.tableView.contentSize.height
self.view.layoutIfNeeded()
}
}
// MARK: - TableView Methods -
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.textLabel?.text = "list cell \(indexPath.row)"
}
}
For the interface layout, I did this:
Add scrollView to main view
Pin scrollview all four sides main view
Add contentView to scrollView
Pin contentView all four sides to scrollView
Make contentView width equal to scrollView width
Add collectionView to contentView
Add tableView to contentView and vertically below collectionView
Pin left, top, right of collectionView to contentView
Pin left, bottom, right of tableView to contentView and top of tableView to bottom of collectionView
Make collectionView height 667 and create IBOutlet NSLayoutConstraint for collectionView height (so we can update it later)
Make tableView height 667 and create IBOutlet NSLayoutConstraint for tableView height (also to update later)
Make collectionView min item spacing 1 and line spacing 1
Disable scrollingEnabled for collectionView
Disable scrollingEnabled for tableView
Connect collectionView datasource and delegate to controller
Connect tableView datasource and delegate to controller
Here's a screenshot of the layout if it's any help.
Usually I build my UI using pure code and you would be able to copy and paste, hit the run button but since you're using using Storyboard, I showed it using Storyboard, hopefully you can follow my layout setup instructions.
Here's the result:
Is that what you wanted?

Related

How to make pagination with UITableView along with UISegmentedControll

My view controller has a UISegmentedControll with 6 buttons/segment. It also has a UITableView under that Segmented Controll. If we switch segment by click then table view is reloading with different data. Now we are trying to implement a way where if user swipe the table view either in left-to-right or right-to-left, a pagination like behaviour will be appeared in the view controller. Means the table view will horizontally scrolled along with segmented controll. How can we implement this feature in my app in best approach ? My table has three different custom cell, one of which also has a UICollectionView inside the cell. Pls help me out. Thanks.
The idea I would suggest is to use tableView inside collectionView. Steps to follow-:
1) Add segmentedControl and collectionView on your controller.
2) Connect dataSource and delegate by control dragging from collectionView to controller yello icon.
3) Adjust your cell height.
4) Select collectionView, and go to attribute inspector. Look for-: 1) scroll direction and make horizontal. 2) Check Paging Enabled parameter.
5) Apply Constraints on views.
6) Give collectionView cell identifier.
7) Give your cell a custom collectionView cell class.
8) Connect all Outlets to respected views.
Controller class -:
import UIKit
class ViewController: UIViewController {
// OUTLETS
#IBOutlet weak var controls: UISegmentedControl!
#IBOutlet weak var horizontalCollectionView: UICollectionView!
// ARRAy OF TYPE UICOLOR
var collectionViewColors = [UIColor.gray,UIColor.green,UIColor.red,UIColor.yellow,UIColor.blue,UIColor.brown]
// ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
}
//didReceiveMemoryWarning
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Function to calculate cell index on scroll end.
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>){
let pagingIndex = targetContentOffset.pointee.x/self.view.frame.width
// Set segmented controll current index
controls.selectedSegmentIndex = Int(pagingIndex)
}
}
// Collection view methods
extension ViewController : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
// number of section
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
// number of items in section
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionViewColors.count
}
// deque cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection", for: indexPath) as! HorizontalCell
cell.horizonatlColorsView.backgroundColor = collectionViewColors[indexPath.item]
return cell
}
// set minimum line spacing to zero.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
Custom cell class-:
import UIKit
class HorizontalCell: UICollectionViewCell {
// UIView outlet
#IBOutlet weak var horizonatlColorsView: UIView!
}
After setting up everything , scroll horizontally you will get the output you want.Also you can add tableView inside collectionView now.
Output-:

Expanding UICollectionView and its cell when tapped

I am trying to make a transition animation like the demonstration in the link here. So when I clicked the cell, it expands and covers the whole screen.
Here are my codes(I have to admit that I am not familiar with CollectionView)`
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet weak var mainDesLabel: UILabel!
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var secDesLabel: UILabel!
let searchBar = UISearchBar()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.backgroundColor = UIColor.clearColor()
////////////////////////////////////////////////////////////////////////
self.searchBar.frame = CGRect(x: 175, y: 0, width: 200, height: 50)
self.searchBar.searchBarStyle = UISearchBarStyle.Minimal
self.searchBar.backgroundColor = UIColor.whiteColor()
self.view.addSubview(searchBar)
////////////////////////////////////////////////////////////////////////
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as UICollectionViewCell
cell.layer.cornerRadius = 5
return cell
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
//Use for size
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.collectionView.frame = self.view.bounds
let cell = collectionView.cellForItemAtIndexPath(indexPath)
cell!.frame = CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height)
}
}
So I thought use 'didSelectItemAtIndexPath' would help, however it turns out like this
thoughts? Any help would be highly appreciated!
Or what you can do is expand the item and change its frame with UIAnimation.
And when he cell is tapped, you get the views inside the cell to be expanded also using auto layout and I'm hinting towards (clips to bounds).
something like this:
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let item = collectionView.cellForItemAtIndexPath(indexPath) as! cellCollectionViewExpress // or whatever you collection view cell class name is.
UIView.animateWithDuration(1.0, animations: {
self.view.bringSubviewToFront(collectionView)
collectionView.bringSubviewToFront(item)
item.frame.origin = self.view.frame.origin /// this view origin will be at the top of the scroll content, you'll have to figure this out
item.frame.size.width = self.view.frame.width
item.frame.size.height = self.view.frame.height
})
}
I would suggest you that you use UICollectionView Controller, so things are at ease in general with using that.
You cannot just use didSelectItemAtIndexPath or any similar methods to update the size of a UICollectionViewCell once the UICollectionView is done performing the view layout.
To update cell height,
You can first capture which cell had been tapped in didSelectItemAtIndexPath.
Then, you can either reload the entire collection view with the new cell frame being passed in the sizeForItemAtIndexpath.
Or, you can just reload the specific cell with reloadItemsAtIndexPaths, but you still need to pass the updated size of the cell via sizeForItemAtIndexpath.
UPDATE
I now see the question details have been updated by an animation which you desire to have.
I had performed a similar animation by:-
Capturing the cell which had been tapped in didSelectItemAtIndexPath.
Adding a replica view to the UIViewContrller, but with its frame totally coinciding with the cell which had been tapped.
Then, animating this view which had been added. Thus giving an impression that the cell was animated.
Any additional functionality which has to be given can also be written in this view. Thus the code of the cell and the animated view is separated too.
When a cell tapped or a button or any tappable thing got tapped inside the cell, then you get the call from
didSelectItemAtIndexPath or through delegate, then to give the cell the required size, you have to invalidate the layout of the current collectionview. After this, size for item will get called and give the new size for the,
This will update the size of the collectioncell without reloading it.
You can give animation also.
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.invalidateLayout()
}
}
extension UICollectionView {
func transactionAnimation(with duration: Float, animateChanges: #escaping () -> Void) {
UIView.animate(withDuration: TimeInterval(duration)) {
CATransaction.begin()
CATransaction.setAnimationDuration(CFTimeInterval(duration))
CATransaction.setAnimationTimingFunction(.init(name: .default))
animateChanges()
CATransaction.commit()
}
}
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.transactionAnimation(with: 0.3) {
self.carInfoCollectionView?.performBatchUpdates({}, completion: { _ in })
}
}

Simply using storyboard, constraints to set size of cell in UICollectionView

Here's a UICollectionView, and the cell in purple:
Quite simply, I want the cells to be 1/2 of the collection view width. (So TBC, it will be a two rows arrangement of cells in the collection view.)
(The collection view is simply fullscreen, so each cell is half the screen width.)
How do you do this in storyboard?
If I try to control-drag in the normal way, it basically doesn't work.
These are simple totally static cells (not dynamic).
For anyone googling here, to save your time: Here's exactly (2016) the simplest way to make a two-across UICollectionView layout; no gaps between the cells.
// Two - two-across UICollectionView
// use a completely standard UIViewController on the storyboard,
// likely change scroll direction to vertical.
// name the cell identifier "cellTwo" on the storyboard
import UIKit
class Two:UICollectionViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
let w = collectionView!.bounds.width / 2.0
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width:w,height:w)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
// Note!! DO NOT!!! register if using a storyboard cell!!
// do NOT do this:
// self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{ return 1 }
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{ return 5 }
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
return collectionView.dequeueReusableCellWithReuseIdentifier("cellTwo", forIndexPath: indexPath)
}
}
You can't do it in the storyboard. The collection view width is not known until runtime, and collection view cells are not under autolayout, so you cannot express the notion "1/2 the width" of anything else. (If you did know the collection view width in advance, you could use the flow layout in the storyboard to set the cell size absolutely, by dividing in your head; but you don't know it, because the width differs depending on the device.)

tableview's Row height is not changing , CollectionView is capturing all the unused space instead of resizing itself in the tableViewCell

I put a UICollectionView into the UITableViewCell by following this tutorial and in my UICollectionViewCell, there's a Image View. So when I run my app, the collection view is not resizing itself at the same time in my cell I put a Text View which is resizing itself according to content, see the below images:
In this first image, I have a text view at the top which have some text in it, and below it with (pink background) is my collection view and inside of that with greenBackground is my image view, as you can see that collection view is taking the extra space instead of reducing itself as Text View Did.
in this second image you can see that my textView haves more content then before so its resized itself now overlapping the CollectionView
this is my TableViewCell:
class TableViewCell: UITableViewCell {
#IBOutlet var txtView: UITextView!
#IBOutlet private weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// collectionView.frame = self.bounds;
// collectionView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setCollectionViewDataSourceDelegate
<D: protocol<UICollectionViewDataSource, UICollectionViewDelegate>>
(dataSourceDelegate: D, forRow row: Int) {
collectionView.delegate = dataSourceDelegate
collectionView.dataSource = dataSourceDelegate
collectionView.tag = row
collectionView.reloadData()
}
var collectionViewOffset: CGFloat {
get {
return collectionView.contentOffset.x
}
set {
collectionView.contentOffset.x = newValue
}
}
}
this is my collectionViewCell
class CollectionViewCell: UICollectionViewCell {
#IBOutlet var imgView: UIImageView!
override func awakeFromNib() {
self.setNeedsLayout()
//
// self.contentView.frame = self.bounds;
// self.contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
}
}
and this is my TableviewController
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return imageModel.count
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell",
forIndexPath: indexPath) as! TableViewCell
cell.txtView.text = txtArray[indexPath.row]
return cell
}
override func tableView(tableView: UITableView,
willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath) {
guard let tableViewCell = cell as? TableViewCell else { return }
tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
}
override func tableView(tableView: UITableView,
didEndDisplayingCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath) {
guard let tableViewCell = cell as? TableViewCell else { return }
storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset
}
}
extension TableViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return imageModel[collectionView.tag].count
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell",
forIndexPath: indexPath) as! CollectionViewCell
cell.imgView.frame = CGRectMake(0, 0, collectionView.frame.width, collectionView.frame.height)
cell.imgView.contentMode = .ScaleAspectFit
//cell.addSubview(imageView)
cell.imgView.image = ResizeImage(UIImage(named: imageModel[collectionView.tag][indexPath.item])!, targetSize: CGSizeMake( cell.imgView.frame.width , cell.imgView.frame.height))
//imageView.image = UIImage(named: imageModel[collectionView.tag][indexPath.item])
return cell
}
}
How can I make this collection view to AutoLayout itself according to the content in it? I also tried this:
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 100;
but didn't worked (my collection view got disappear) if anybody knows how to do this, then please guide me..
I faced a similar issue when i used collection view inside a table view cell. No matter what i did i couldn't get the table view to resize automatically but the collection view did. Soo instead of autolayout i did it using code.
I ended up having to calculate the size of the label in the collection view numberOfSections in collection view and passing this height using a delegate to the view controller that has the tableView's delegate and dataSource and reloading the appropriate row of the table view.
As it happens, the numberOfSections in collectionview data source gets called everytime and the delegate resizes the table view height.
Some thing like this-
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
[self.delegate setViewHeight:[self getHeightForCellAtIndexPath:[NSIndexPath indexPathForRow:currentSelected inSection:0]]];
return 1;
}
This ought to give you a general idea.
EDIT: Sorry i misunderstood, your question before. Here is something that should work for you:
As per my understanding, you have a table view cell with a label view and collection view inside of it.
Now, inside your table view cell, you should add top, leading and trailing constraints space to the label. Now inside your collection view position your image vertically in the center and add an appropriate top and bottom to the cell superview. Your collection view itself should have a CONSTANT value in leading, trailing, top to label and bottom to superview. Also add a fixed height constraint to your collection View (assuming you want the image sizes to remain the same).
Now lets says View Controller A is the data source for your table view and the table view cell is the data source for your collection view.
In your viewController A, you should write your height for row at indexPath as-
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGSize stringSize = [yourStringArray[indexPath.row] boundingRectWithSize:CGSizeMake(_yourCollectionView.frame.size.width, FLT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName:[UIFont yourFont size:yourFontSize]} context:nil].
return stringSize.height + 35; //magic number 35, play around with it to suit your need. Did this to always have a minimum fixed height.
}
This will allow your tableViewRowForHeight for that particular index to have the height of your label added to it and the constraints ought to do the rest.

Fix the aspect ratio of the first row in UITableView

I'm creating a screen, imagine the facebook profile screen.. A tableview and the first cell is an image. The goal is that this image maintains an aspect ratio, so with different screen sizes I don't have to worry about sizing it..
I can't get this to work with any view, even if I set specific constraints, the cell won't set the correct height..
I have a little project showing constraints, in this link..
My VC Code:
class ViewController: UITableViewController{
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.estimatedRowHeight = 100
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
}
My constrains:
If the height of the table view cell is basically a function of the table view's width, it might be easier to implement the heightForRowAtIndexPath delegate method to return the width of the table view multiplied by the ratio you want. That would take constraints out of the picture entirely, and probably be more efficient.
This is what you should do:
Insert a table view header view
Update the frame height keep the desired aspect ratio in the viewWillLayoutSubviews function.
class ViewController: UITableViewController {
#IBOutlet weak var headerView: UIView!
override func viewWillLayoutSubviews() {
var frame = headerView.frame;
// Check and see if the aspect ratio of the frame
// of the header view is the desired aspect ratio.
if frame.size.height != frame.width * 0.5 {
// If it is not, update the frame
frame.size.height = frame.width * 0.5;
headerView.frame = frame;
// reset the header view
self.tableView.tableHeaderView = headerView
}
}
}

Resources