How to change the Title label text alignment of the section when it was present - ios

I'm loading the UITableView with two section and I've used viewForHeaderInSection method to set the title for each section. Initially I've set the title label text alignment as .left. Now when I scroll the table view and the second section was present i want to change the title label text alignment to .center. And when I scroll down the table view i want to show as initial(like second section text alignment as .left). How can I Do that?
Here is the TableView Delegatemethod I've used to load the section.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerLabel:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 20))
headerLabel.textColor = UIColor.white
headerLabel.textAlignment = .left
headerLabel.font = Fonts.kFontWith_14
if section == 0
{
headerLabel.text = NSLocalizedString("Suggested", comment: "")
headerLabel.backgroundColor = Colors.kAppBgColor
headerLabel.textAlignment = .left
}
else{
headerLabel.text = NSLocalizedString("Contacts", comment: "")
headerLabel.backgroundColor = Colors.kLightBlueColor
headerLabel.textAlignment = .left
}
headerLabel.sizeToFit()
return headerLabel
}

Take one bool variable on global, The follwoing delegate will respond you when scroll happens
var isDirection = Bool()
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if velocity.y > 0 {
print("up")
isDirection = true
}
if velocity.y < 0 {
print("down")
isDirection = false
}
}
Then write a condition in respective `tableview` delegate
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerLabel:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 20))
headerLabel.textColor = UIColor.white
headerLabel.textAlignment = .left
headerLabel.font = Fonts.kFontWith_14
if section == 0
{
headerLabel.text = NSLocalizedString("Suggested", comment: "")
headerLabel.backgroundColor = Colors.kAppBgColor
}
else{
headerLabel.text = NSLocalizedString("Contacts", comment: "")
headerLabel.backgroundColor = Colors.kLightBlueColor
}
if isDirection{
headerLabel.textAlignment = .left
}else{
headerLabel.textAlignment = .center
}
return headerLabel
}
Remove
headerLabel.sizeToFit()
This is sample, you enable bool variable based on your scroll direction. If delegate does not call, reload your table on scrollViewWillEndDragging

Here is the way for my problem
Take a bool value and a CGPoint globally and assign the UITableView.ContentOffset value to the defaultOffset in viewDidload Method.
var isScroll:Bool = Bool()
var defaultOffSet = CGPoint()
override func viewDidLoad() {
super.viewDidLoad()
defaultOffSet = tableView.contentOffset
}
And I've used this scrollView delegate method
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if contactsTableView.rectForHeader(inSection: 1).origin.y > contactsTableView.contentOffset.y-defaultOffSet.y {
isScrolled = false
}
else if tableView.rectForHeader(inSection: 0).origin.y <= tableView.contentOffset.y-defaultOffSet.y{
isScrolled = true
}
tableView.reloadData()
}
And In my tableview viewForHeaderInSection
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerLabel:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 20))
headerLabel.textColor = UIColor.white
headerLabel.textAlignment = .left
headerLabel.font = Fonts.kFontWith_14
if section == 0
{
headerLabel.text = NSLocalizedString("Suggested", comment: "")
headerLabel.backgroundColor = Colors.kAppBgColor
headerLabel.textAlignment = .left
}
else{
headerLabel.text = NSLocalizedString("Contacts", comment: "")
headerLabel.backgroundColor = Colors.kLightBlueColor
if isScrolled{
headerLabel.textAlignment = .center
headerLabel.backgroundColor = Colors.kAppBgColor
}
}
}
}

Related

There is change add to atop duplicate header, but there is a stretch effect?

enter image description hereThere is a stretch effect.But the additional header is duplicated , only without data.Can anyone correct my code that I wrote extra or incorrectly called the header?.I have custom Header xib. link tutorial https://mobikul.com/table-view-stretch-header-parallax-animation-in-swift/
My code:
var headerView: CustomSoccerHeaderView? = {
return Bundle.main.loadNibNamed("CustomSoccerHeaderView", owner: nil, options: nil)!.first as! CustomSoccerHeaderView
}()
override func viewDidLoad() {
super.viewDidLoad()
let backButton = UIBarButtonItem()
backButton.title = ""
self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
// self.navigationItem.rightBarButtonItem = barButton
// self.navigationItem.rightBarButtonItem?.tintColor = UIColor.universalColorYellow
let yourBackImage = UIImage(named: "backItem")
self.navigationController?.navigationBar.backIndicatorImage = yourBackImage
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = yourBackImage
self.navigationController?.navigationItem.leftItemsSupplementBackButton = true
self.navigationController?.navigationBar.tintColor = UIColor.universalColorYellow
//title = detailSoccer.detailTitleS
let nib: UINib = UINib(nibName: "CustomSoccerHeaderView", bundle: nil)
tableView.register(nib, forHeaderFooterViewReuseIdentifier: "CustomSoccerHeaderView")
tableView.tableFooterView = UIView(frame: .zero)
tableView.estimatedRowHeight = 280
headerView?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 350)
tableView.tableHeaderView = headerView
tableView.tableHeaderView = nil
tableView.contentInset = UIEdgeInsets(top: 350, left: 0, bottom: 0, right: 0)
tableView.addSubview(headerView!)
tableView.separatorStyle = .none
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName:"FootTableViewCell",bundle:nil), forCellReuseIdentifier: "cellSoc")
self.view.addSubview(tableView)
tableView.rowHeight = UITableView.automaticDimension
tableView.reloadData()
loadMatchSoccer()
tableView.rowHeight = UITableView.automaticDimension
}
That's going to stretch the effect:
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
self.tableView.reloadData()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if headerView != nil {
let yPos: CGFloat = -scrollView.contentOffset.y
if yPos > 0 {
var imgRect: CGRect? = headerView?.frame
imgRect?.origin.y = scrollView.contentOffset.y
imgRect?.size.height = 350 + yPos - 350
headerView?.frame = imgRect!
self.tableView.sectionHeaderHeight = (imgRect?.size.height)!
}
}
}
This is the code for the header section of my file xib class.I think I make a mistake in inheriting the header or loading addsubview.Maybe someone more experienced can tweak my code.I would appreciate that.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomSoccerHeaderView") as! CustomSoccerHeaderView
header.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 350)
header.clickBravisso = detailSoccer
header.nameHeader.text = detailSoccer.matchS
header.countBravo.text = ""
// header.bravoBtn.addTarget(CustomSoccerHeaderView(), action: #selector(CustomSoccerHeaderView.likeBtn(_:)), for: UIControlEvents.touchUpInside)
detailSoccer.imagePrS.getDataInBackground { (data, error) in
header.imageHeader.image = error == nil ? UIImage(data: data!) : nil
}
return header
}

No results label on empty tableView

I am adding "No results" label if tableView is empty.
extension UITableView {
override open func layoutSubviews() {
print("Table layoutSubviews")
let label = UILabel(frame: self.bounds)
if self.visibleCells.isEmpty {
label.center = self.center
label.text = "No Results"
label.textAlignment = .center
if label.superview == nil {
self.addSubview(label)
}
} else {
label.removeFromSuperview()
}
}
}
But that doesn't work on updating/Reloading tableView(on row change).
It still show "No Result" on non empty UITableView
extension UITableView {
func setMessage(_ message: String) {
let lblMessage = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
lblMessage.text = message
lblMessage.textColor = .black
lblMessage.numberOfLines = 0
lblMessage.textAlignment = .center
lblMessage.font = UIFont(name: "TrebuchetMS", size: 15)
lblMessage.sizeToFit()
self.backgroundView = lblMessage
self.separatorStyle = .none
}
func clearBackground() {
self.backgroundView = nil
self.separatorStyle = .singleLine
}
}
Now use this extension as like below
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if items.count == 0 {
tableView.setMessage("No results")
} else {
tableView.clearBackground()
}
return items.count
}
Create Swift Class With Name "TableViewHelper".
You Can also Used In a CollectionView.
import UIKit
class TableViewHelper {
class func EmptyMessage(message:String, tableview:UITableView,vc:UIViewController) {
let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: vc.view.bounds.size.width, height: vc.view.bounds.size.height))
let messageLabel = UILabel(frame: rect)
messageLabel.text = message
messageLabel.textColor = UIColor.white
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center
messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
messageLabel.sizeToFit()
tableview.backgroundView = messageLabel;
tableview.separatorStyle = .none;
}
}
class ColelctionViewHelper {
class func EmptyMessage(message:String, collectionview:UICollectionView,vc:UIViewController) {
let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: vc.view.bounds.size.width, height: vc.view.bounds.size.height))
let messageLabel = UILabel(frame: rect)
messageLabel.text = message
messageLabel.textColor = UIColor.white
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center
messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
messageLabel.sizeToFit()
collectionview.backgroundView = messageLabel;
// collectionview.separatorStyle = .none;
}
}
This Is How You Use It,
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if YourArray.count>0{
TableViewHelper.EmptyMessage(message: "", tableview: TableName,vc: self)
return EventArray.count
}else{
TableViewHelper.EmptyMessage(message: "No Results", tableview: TableName,vc: self)
return 0;
}
}

UIActivityIndicatorView disappears in CollectionView Footer

I have a collectionView with only 1 section in my app which download data from API. I have a pagination and I am trying to add a loading footer in my collectionView. The header appears normally. I have in this footer cell an UIActivityIndicatorView and a UILabel. When the first at a limit is triggered, the 2 elements are present in the cell but when the second limit is triggered, the UIActivityIndicatorView is absent.
Have you an idea for that.
The code of the cell (BaseCell is just a class to avoid tapping the init and required init each time):
class loadingCell: BaseCell {
override func setupViews() {
super.setupViews()
backgroundColor = .yellow
let activity = UIActivityIndicatorView()
activity.backgroundColor = .red
activity.startAnimating()
activity.frame = CGRect(x: 10, y: 20, width: 20, height: 20)
let label = UILabel()
label.text = "hello"
label.frame = CGRect(x: 100, y: 20, width: 40, height: 20)
label.backgroundColor = .green
addSubview(activity)
addSubview(label)
}
}
The collection delegate methods :
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: SCREENW, height: 50)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionFooter {
let loadingFooterView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: loadingCell, for: indexPath)
return loadingFooterView
}
return UICollectionReusableView()
}
The cell is well registered.
What happens when first limit is triggered:
And with the second:
Based on #MaksymMusiienko comment, I have tried this which do the job to reset the animation of the spinner.
class loadingCell: BaseCell {
let activitySpinner: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView()
spinner.backgroundColor = .red
spinner.startAnimating()
spinner.frame = CGRect(x: 10, y: 20, width: 20, height: 20)
return spinner
}()
override func setupViews() {
super.setupViews()
backgroundColor = .yellow
let label = UILabel()
label.text = "hello"
label.frame = CGRect(x: 100, y: 20, width: 40, height: 20)
label.backgroundColor = .green
addSubview(activitySpinner)
addSubview(label)
}
override func prepareForReuse() {
super.prepareForReuse()
activitySpinner.startAnimating()
}
}

how can I display the following scenes hierarchy in swift using collectionView?

I have the following display scenes available. I am getting confused what type of hierarchy of controls I should take to display these type of view in xib .
please give ideas to show these types of scenes. because my items are coming dynamically . Its not fixed. so if I took tableview to display the first items and its categories then where should i display the rest items.
Edited
I took four sections. In 1st section collection and delivery buttons. In 3rd notes and in 4th allergy & checkout .
In 2nd my order items are there. but here I have two level of data.. order item name like chicken kabab small,... etc and 2nd level its addons like plain nan, bottle of drink,... etc. Here my order items is iterating in cell as well as my addons are iterating. I took the order items name in cell. now where should i take the addon items programatically and how to set the size of each cell based on its all contents inside it.
class cartVC: UIViewController ,UITableViewDataSource,UITableViewDelegate,UITextViewDelegate{
var tableData = ["al","dbd","gdge","kjdkas","al","dbd","gdge","kjdkas","al","dbd","gdge","kjdkas","al","dbd","gdge","kjdkas"]
var mainview = UIView()
#IBOutlet weak var cartTableView: UITableView!
#IBAction func backBtn(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func changeColor(sender:UISegmentedControl){
switch(sender.selectedSegmentIndex){
case 0:
print("collection clicked")
case 1:
print("delivery clicked")
default:
self.view.backgroundColor = UIColor.blueColor()
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 4
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowcount = 0
if section == 0{
rowcount = 0
}
if section == 1 {
rowcount = tableData.count
}
if section == 2{
rowcount == 0
}
if section == 3{
rowcount == 0
}
return rowcount
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0{
let headerView = UIView()
//set the frame
let frame = UIScreen.mainScreen().bounds
// headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 60)
headerView.frame = CGRectMake(frame.minX , frame.minY, frame.width, 60)
headerView.backgroundColor = UIColor.whiteColor()
//Initialize segment control
let items = ["Collection","Delivery"]
let customSC = UISegmentedControl(items: items)
customSC.selectedSegmentIndex = 0
//set the frame amd segmented control
customSC.frame = CGRectMake(frame.minX + 10, frame.minY + 5, frame.width - 20, 30)
// style the segmented control
customSC.layer.cornerRadius = 5.0
customSC.backgroundColor = UIColor.clearColor()
customSC.tintColor = UIColor.redColor()
//add target action method
customSC.addTarget(self, action: #selector(CartViewController.changeColor(_:)), forControlEvents: .ValueChanged)
//add subview
headerView.addSubview(customSC)
//Add label
let headinglbl = UILabel(frame: CGRect(x: frame.minX + 10, y: frame.minY + 40, width: tableView.frame.size.width, height: 20))
headinglbl.text = "Your Order"
headinglbl.font = UIFont.boldSystemFontOfSize(17)
headinglbl.textColor = UIColor.blackColor()
headinglbl.textAlignment = .Center
headerView.addSubview(headinglbl)
mainview = headerView
}
if section == 2{
let totalView = UIView()
totalView.frame = CGRectMake(0, 0, tableView.frame.size.width, 60)
totalView.backgroundColor = UIColor.clearColor()
//Add discount label
let discount = 14.5
let discountlbl = UILabel(frame: CGRectMake(10, 0, tableView.frame.size.width, 20))
discountlbl.text = "Online Collection Discount(\(discount)%)"
discountlbl.font = UIFont.systemFontOfSize(14)
discountlbl.textColor = UIColor.darkGrayColor()
discountlbl.textAlignment = .Left
totalView.addSubview(discountlbl)
//Add discount price
let discountprice = UILabel(frame: CGRectMake(tableView.frame.size.width-60, 0, tableView.frame.size.width, 20))
discountprice.text = "£ 1.27"
discountprice.font = UIFont.systemFontOfSize(14)
discountprice.textColor = UIColor.blackColor()
discountprice.textAlignment = .Left
totalView.addSubview(discountprice)
//Add label
let lbl = UILabel(frame: CGRectMake(10, 20, tableView.frame.size.width, 40))
lbl.text = "Total"
lbl.font = UIFont.boldSystemFontOfSize(20)
lbl.textColor = UIColor.blackColor()
lbl.textAlignment = .Left
totalView.addSubview(lbl)
//calculate amount label
let totalAmountLbl = UILabel(frame: CGRectMake(totalView.frame.width-70, 20, totalView.frame.width, 40))
totalAmountLbl.text = "£ 0.0"
totalAmountLbl.font = UIFont.boldSystemFontOfSize(20)
totalAmountLbl.textColor = UIColor.blackColor()
totalAmountLbl.textAlignment = .Left
totalView.addSubview(totalAmountLbl)
mainview = totalView
}
if section == 3{
let footerView = UIView()
footerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 200)
footerView.backgroundColor = UIColor.clearColor()
//Add note label
let notelbl = UILabel(frame: CGRectMake(10, 10, tableView.frame.size.width, 20))
notelbl.text = "Leave a note"
notelbl.font = UIFont.boldSystemFontOfSize(17)
notelbl.textColor = UIColor.blackColor()
notelbl.textAlignment = .Left
footerView.addSubview(notelbl)
//Add a note textview
let noteTxt = UITextView()
noteTxt.frame = CGRectMake(10, 40, footerView.frame.width-20, 50)
noteTxt.backgroundColor = UIColor.lightGrayColor()
noteTxt.keyboardType = UIKeyboardType.Default
noteTxt.text = "e.g. Instructions about yout order"
noteTxt.textColor = UIColor.blackColor()
noteTxt.delegate = self
footerView.addSubview(noteTxt)
// Add allergy button
let allergyBtn = UIButton(type:.System)
allergyBtn.frame = CGRectMake(50, 100, 200, 20)
allergyBtn.setTitle("Do You have any allergy ?", forState: .Normal)
allergyBtn.setTitleColor(UIColor.redColor(), forState: .Normal)
allergyBtn.titleLabel?.font = UIFont(name: "", size: 10)
footerView.addSubview(allergyBtn)
// Add checkout button
let checkoutBtn = UIButton(type:.System)
checkoutBtn.frame = CGRectMake(100, 140, 100, 40)
checkoutBtn.setTitle("Check out", forState: .Normal)
checkoutBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
checkoutBtn.titleLabel?.font = UIFont(name: "", size: 10)
checkoutBtn.backgroundColor = UIColor.redColor()
checkoutBtn.layer.cornerRadius = 5
footerView.addSubview(checkoutBtn)
mainview = footerView
}
return mainview
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cartcell")! as! CartTableViewCell
cell.itemLabel.text = tableData[indexPath.row]
return cell
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
var heightCount:CGFloat = 0
if section == 0{
heightCount = 60.0
}
if section == 2{
heightCount = 60.0
}
if section == 3{
heightCount = 200.0
}
return heightCount
}
My customcell code
import UIKit
class CartTableViewCell: UITableViewCell {
let padding: CGFloat = 5
var background: UIView!
var itemLabel: UILabel!
var priceLabel: UILabel!
var deleteBtn:UIButton!
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clearColor()
selectionStyle = .None
background = UIView(frame: CGRectZero)
background.alpha = 0.6
contentView.addSubview(background)
deleteBtn = UIButton(frame: CGRectZero)
deleteBtn.setImage(UIImage(named: "deleteBin.png"), forState: .Normal)
contentView.addSubview(deleteBtn)
itemLabel = UILabel(frame: CGRectZero)
itemLabel.textAlignment = .Left
itemLabel.textColor = UIColor.whiteColor()
contentView.addSubview(itemLabel)
priceLabel = UILabel(frame: CGRectZero)
priceLabel.textAlignment = .Center
priceLabel.textColor = UIColor.whiteColor()
contentView.addSubview(priceLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
background.frame = CGRectMake(0, padding, frame.width, frame.height-2 * padding)
deleteBtn.frame = CGRectMake(padding, (frame.height - 25)/2, 40, 25)
priceLabel.frame = CGRectMake(frame.width-100, padding, 100, frame.height - 2 * padding)
itemLabel.frame = CGRectMake(CGRectGetMaxX(deleteBtn.frame) + 10, 0, frame.width - priceLabel.frame.width - CGRectGetMaxX(deleteBtn.frame) + 10, frame.height)
}
}
As our mates already said about using tableview and sections, Here we gonna follow the same way.Since it is a broad topic to explain i'll give some hint and at last you can find link for demo project.
First add a tableview in your storyboard then add collection,Delivery & Your order objects as tableview header
Create a new class subclass of UITableviewcell with xib let's name it as Cell1.Now add delete icon, main dish label and price label,for sub items we gonna use another UITableview.
Now create another UITableviewcell with xib name it as Cell2, prepare that xib for sub items and their price.
In cell1 numberOfSectionsInTableView return number of main dish count and in numberOfRowsInSection return 1, Now load name of all main dishes in their respective label's
Upto now we having some number of section(depending on number of main items) each section having one UITableview.
Now we have to change height of tableview cell dynamically depending on SubItems count. so in heightForRowAtIndexPath i have added following lines
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let subItems = tableContainer![indexPath.section].valueForKey("additional_items") as! NSArray
var defaultCellHeight:CGFloat = 37//Consider 37 as height of cell without subitems
//Following for loop keeps on increasing defaultCellHeight depending on available count
for _ in subItems {
defaultCellHeight += 37
}
return defaultCellHeight + 20
}
Since it is hard to explain everything deeply i have provide code for heightForRowAtIndexPath.While looking into the demo project you'll understand everything
NOTE : Upto now we have loaded all main dishes details, and we have provided enough room for upcoming sub item's.
In Cell1 class add tableview delegate and datasource in awakeFromNib,add all datasource methods as required.set numberOfSectionsInTableView as 1 and numberOfRowsInSection as subitem count
That's it we have loaded tableview dynamically as per your requirement.
Now at last add discount, total, leave a note& Checkout objects in separate tableviewcell class an load it at last index.
Or add add all those objects inside a UIView and add it as Main tableview's footer.
NOTE : The above hints are just for reference, For better clarification of concept i have added a demo project's github repo.
RESULT :

Different height in custom UITableViewCell

I want to create a custom UITableViewCell programmatically and cells have different height. But the height is fixed.
SingeTableViewCell.swift
class SingleTableViewCell: UITableViewCell {
var title = UILabel()
var content = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
self.setSeparator()
self.setTitle()
self.setContent()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setSeparator() {
let separator = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 10))
separator.backgroundColor = UIColor(hex: "#E7EBF2")
contentView.addSubview(separator)
}
func setTitle() {
let viewTitle = UIView(frame: CGRectMake(0, 10, UIScreen.mainScreen().bounds.width, 40))
viewTitle.backgroundColor = UIColor(hex: "#EEE")
viewTitle.layer.borderColor = UIColor.lightGrayColor().CGColor
viewTitle.layer.borderWidth = 1.0
self.title = UILabel(frame: CGRectMake(5, 0, UIScreen.mainScreen().bounds.width-5, 40))
self.title.textAlignment = NSTextAlignment.Center
self.title.font = self.title.font.fontWithSize(13)
viewTitle.addSubview(self.title)
contentView.addSubview(viewTitle)
}
func setContent() {
self.content = UILabel(frame: CGRectMake(0, 50, UIScreen.mainScreen().bounds.width, 400))
self.backgroundColor = UIColor.whiteColor()
contentView.addSubview(self.content)
}
}
I want cell's height is equals to frame's height.
Thank you and sorry for my bad english.
You can use Auto Layout to set self-sizing cell. Working with Self-Sizing Table View Cells
Alternatively, you can set the height with - tableView:heightForRowAtIndexPath: in UITableViewDelegate
class ViewController: UIViewController, UITableViewDelegate{
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// assume that you want to set height equal to 300 in 1st secion, and 200 in 2nd section.
let heights: [CGFloat] = [ 300,200 ]
return heights[indexPath.section]
}
}

Resources