tableView not appearing in ViewController (swift) - ios

While running the code in XCode 6.1 nothing appears in the ViewController.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView!
var messages: [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(self.tableView)
//http://stackoverflow.com/questions/25413239/custom-uitablecellview-programmatically-using-swift
//Auto-set the UITableViewCells height (requires iOS8)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
// add something to messages
messages.append("foo")
messages.append("bar")
}
// TABLEVIEWS
//func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
// return 1
//}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count = messages.count ?? 0
NSLog("message count: \(count)")
return count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//var cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as MyCell
var cell = UITableViewCell()
NSLog("row[\(indexPath.row)]: \(messages[indexPath.row])")
cell.textLabel.text = messages[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Try this Code:
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(self.tableView)
//Auto-set the UITableViewCells height (requires iOS8)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
tableView.frame = CGRectMake(0, 0, 320, 568)
// add something to messages
messages.append("foo")
messages.append("bar")
}
EDIT:Try this for all size of screen :
tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)

Hmm why make it so hard for your self. In the story board you can either add a TableViewController to the project or add a tableview to you viewcontroller and it will work out of the box. The controller class should inherit from UITableViewController.

Related

UiView fixed on top of UiTableViewController

I need to put an UIView fixed on top of UITableViewController (like a header). I've tried this:
override func scrollViewDidScroll (scrollView: UIScrollView) {
var fixedFrame: CGRect = self.uiTopView.frame;
fixedFrame.origin.y = scrollView.contentOffset.y;
self.uiTopView.frame = fixedFrame;
}
But it does not work and I don't know why. Someone have any idea?
This can not be done, one way to accomplish this is to add the UITableViewController insideUIContainerView
So the structure will be as follows:
ViewController1 contains aUIContainerView this container view has embedded segue
to your tableViewController.
Then you can add the view to the ViewController1.
Why do you actually use UITableViewController instead of UIViewController with a tableView inside?
Maybe you should add your header view first then add you tableview depending on the header's frame.
for example: `import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var fixedLabel : UILabel!
var tableView : UITableView!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tableView.frame = CGRectMake(0, self.fixedLabel.frame.maxY, self.view.frame.width, self.view.frame.height-70)
self.fixedLabel.frame = CGRectMake(0,0,self.view.bounds.width,70)
}
override func viewDidLoad() {
super.viewDidLoad()
self.fixedLabel = UILabel()
self.fixedLabel.backgroundColor = UIColor.blueColor()
self.fixedLabel.text = "This is a fixedLabel"
self.fixedLabel.textAlignment = .Center
self.tableView = UITableView()
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(fixedLabel)
self.view.addSubview(tableView)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cell")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
}
cell?.textLabel?.text = "Your text"
return cell!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
}
`

Can't add UITableView to UIView swift

I have a UIViewController with a header subview and a UITableView.
My tableView with its custom cells works perfectly when I implement it on a UITableView class, but once I try to imbed it in my UIViewController, I get the tableview frame that I see based on the different background color but it doesn't get populated with my custom cell.
My print statement in tableview (...cellForRowAtIndexPath ..) doesn't print anything, it's as if the function is not called.
I'm not sure what I'm doing wrong, any help is much appreciated!
import UIKit
class ProfileViewController: UIViewController , UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView!
var header: UIView!
var userName: UILabel!
var userImage: UIImageView!
var dataDict : NSDictionary!
var cellArray: NSArray!
var friends = [Friends]()
init(dataDict: NSDictionary , nibName: String?, bundle: NSBundle?){
super.init(nibName: nibName, bundle: bundle)
self.dataDict = dataDict
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
cellArray = dataDict?.objectForKey("data") as! NSArray
tableView.delegate = self
tableView.dataSource = self
header = UIView(frame: CGRectZero)
header.backgroundColor = UIColor( red:77/255.0, green:255/255.0, blue:195/255.0, alpha:1.0)
userName = UILabel(frame: CGRectZero)
userName.textAlignment = .Left
userName.text = "Nachwa El khamlichi"
userName.textColor = UIColor.blackColor()
userName.frame = CGRectMake(10, 100, self.view.frame.width/2, 40)
userImage = UIImageView(frame: CGRectZero)
userImage.frame = CGRectMake(10, 30, 80, 80)
tableView.contentInset = UIEdgeInsets(top: 300, left: 0, bottom: 0, right: 0)
tableView.backgroundColor = UIColor.orangeColor()
tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
self.view.addSubview(header)
self.view.addSubview(userName)
self.view.addSubview(userImage)
self.view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print(cellArray.count)
let cell = tableView.dequeueReusableCellWithIdentifier( NSStringFromClass(Cell), forIndexPath: indexPath) as! Cell
let friendName = cellArray[indexPath.row]["name"] as? String
let avatarId = cellArray[indexPath.row]["id"] as? String
friends.append(Friends(name: friendName!, avatarId: avatarId!))
cell.friend?.name = friendName
cell.friend = friends[indexPath.row]
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 40
}
}
I think you forget to add
tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(self.tableView)
at the same time you forget to add frame
header = UIView(frame: CGRectZero)
header.frame = CGRectMake(10, 100, self.view.frame.width/2, 40)
header.backgroundColor = UIColor( red:77/255.0, green:255/255.0, blue:195/255.0, alpha:1.0)
OPtion-2
if every thing is fine check once
your cellArray contains data available or not`,
option-3
after this line add this
self.view.addSubview(self.tableView)
tableView.reloadData()

UITableView embedded in UIView, empty rows

I am working on a new application and I have some problems:
I am developing everything programmatically, so I created a SCROLLVIEW and a CONTAINERVIEW for all my pages. containerView is embedded in scrollView.
Every page has a different Controller, in this case "SearchViewController".
The containerView contains the UIView "selectView" that belongs to "SearchViewController". See below:
let scrollView: UIScrollView = UIScrollView()
let containerView: UIView = UIView()
//SCROLLVIEW
scrollView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height)
self.view.addSubview(scrollView)
//CONTAINERVIEW
containerView.frame = CGRectMake(menuWidth, 0, view.frame.width, view.frame.height)
containerView.backgroundColor = UIColor.whiteColor()
scrollView.addSubview(containerView)
let s: SearchViewController = SearchViewController()
s.setup(bannerHeight, containerViewWidth: containerView.frame.width, containerViewHeight: containerView.frame.height)
containerView.addSubview(s.selectView)
import UIKit
class SearchViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {
let selectView: UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
}
let table: UITableView = UITableView()
var items: [String] = ["A", "B", "C"]
var filteredItems = [String]()
func setup(bannerHeight: CGFloat, containerViewWidth: CGFloat, containerViewHeight: CGFloat){
//SELECT PAGE
selectView.frame = CGRectMake(0, bannerHeight, containerViewWidth, containerViewHeight - bannerHeight)
//UITABLEVIEW
table.frame = CGRectMake(0, 0, selectView.frame.width, selectView.frame.height)
table.delegate = self
table.dataSource = self
table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
selectView.addSubview(table)
}
func numberOfSectionsInTableView(tableView:UITableView)->Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("tableViewCOUNT")
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("tableViewMAIN")
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel!.text = items[indexPath.row]
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
}
So now i have this hierarchy: ScrollView<-containerView<-selectView<-table
The problem is that no data appear! In output I can see "tableViewCOUNT" but never "tableViewMAIN" and except for the empty rows there are no data.
Could somebody help me to understand why?
Am I using the correct way? I would like to have a mainController and for every page a subController, then I will embed the page I need inside the containerView (like an iframe in html).
Thank you in advance!
Try calling
table.reloadData()
in the setup.

UITableView inside a ViewController with custom cell without storyboard

I'm working with Swift 2.0 and Xcode 7.2.
I want to learn how to make an app without a storyboard (UI with pure programming code). To start off, I am trying to make a simple app, with three labels, inside a custom UITableView cell which will be updated dynamically through the internet.
Here is what I have achieved so far:
Created a new Swift project and deleted the main.storyboard from the project
Added a view controller as the rootViewController in AppDelegate
Included code to create a UITableView inside this view
Here are the other tasks I want to accomplish (all programmatically, without using the attribute inspector):
Insert a UINavigationController into the ViewController
Add a custom cell with three labels
Update the table view with data
If possible, I would want to have the ability to have everything working in landscape mode as well.
Can anyone tell me how to do this?
AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window!.backgroundColor = UIColor.whiteColor()
window!.rootViewController = ViewController()
window!.makeKeyAndVisible()
return true
}
ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = UIColor.whiteColor()
tableView.frame = CGRectMake(0 , 0, self.view.bounds.width, self.view.bounds.height)//Optional for table size
self.view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "myIdentifier")
myCell.textLabel?.text = "\(indexPath.row)"
myCell.detailTextLabel?.text = "Subtitle"
return myCell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I have no idea how to create a custom cell programmatically to which I can add objects.
Help would be appreciated.
Thanks.
If you are not using storyboard, you can define your cell just above the class where your ViewController where your are including your tableView something like myCell which is your custom UITableViewCell as given below.
In this myCell, you can add as many objects as your want and set them up in the setUpCell() block.
The full code is as below, please make sure you call setUpCell() when you use your cell's in cellForRowAtIndexPath.
ViewController.swift
import #UIKit
class myCell: UITableViewCell {
// Define label, textField etc
var aMap: UILabel!
// Setup your objects
func setUpCell() {
aMap = UILabel(frame: CGRectMake(0, 0, 200, 50))
self.contentView.addSubview(aMap)
}
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView = UITableView()
// for ex, lets say, your data array is defined in the variable below
var dataArray = [[String:AnyObject]]() //Array of your data to be displayed
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = UIColor.whiteColor()
// register your class with cell identifier
self.tableView.registerClass(myCell.self as AnyClass, forCellReuseIdentifier: "Cell")
self.view.addSubview(tableView)
dataArray = // Something loaded from internet
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return flightDataArr.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let myCell = tableView.dequeueReusableCellWithIdentifier("myIdentifier", forIndexPath: indexPath)
var cell:myCell? = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? myCell
if cell == nil {
cell = myCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
var data = dataArray[indexPath.row]
cell?.setUpCell()
cell!.aMap.text = String(dict["productName"])
return cell!
}
}
See if this works for you. I never used programming to create tableView, so this may not be the optimal way to create your tableView programmatically. I hope someone else may help you with a better answer if possible.
You can create a sub class of UITableViewCell say PackageListTableViewCell.
Declare number of labels in tabelViewCell custom class as per your requirements like below,
var label1 : UILabel?;
override init:reuseIdentifier: in custom cell with additional parameters as below.
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
//create labels as per your requirement
self.label1 = //initialise you label
//set frame, or constraint
//set text color, background color etc
//add created labels to cell as below
self.contentView.addSubView(self.label1);
}
your tableView:cellForRowAtIndexPath: will be look like,
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let lable1String = "lbl1"
let lable2String = "lbl2"
let lable3String = "lbl3"
var cell : PackageListTableViewCell! = tableView.dequeueReusableCellWithIdentifier("cellID") as?PackageListTableViewCell
if (cell == nil) {
cell = PackageListTableViewCell.init(style: UITableViewCellStyle.Default,
reuseIdentifier:"cellID");
}
cell.selectionStyle = UITableViewCellSelectionStyle.None;
//set text of your lables as below
cell.label1.text = lable1String;
return cell;
}
You have to register a custom tableviewcell class using method registerClass on tableview.
Use this modified Viewcontroller code:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = UIColor.whiteColor()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myIdentifier")
tableView.frame = CGRectMake(0 , 0, self.view.bounds.width, self.view.bounds.height)//Optional for table size
self.view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("myIdentifier", forIndexPath: indexPath)
myCell.textLabel?.text = "\(indexPath.row)"
myCell.detailTextLabel?.text = "Subtitle"
return myCell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Receiving nil for UIElements inside tableViewCell added via storyboard

I have created a TableViewCell entirely in storyboard just as I have in any other app. I want to set the properties however the components inside of it (such as cellScrollView) are returning nil. They are connected via IBOutlet. I have never had this happen to me before, the line where is error occurs is :
cell.cellScrollView.contentSize = CGSizeMake((2 * cell.frame.size.width), cell.frame.size.height)
And the error is:
fatal error: unexpectedly found nil while unwrapping an Optional value
Below is the ViewController..
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
#IBOutlet weak var scrollView: UIScrollView!
func random() -> CGFloat { return CGFloat(rand()) / CGFloat(RAND_MAX) }
func randomColor() -> UIColor { return UIColor(red: random(), green: random(), blue: random(), alpha: 1.0) }
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 3, self.view.frame.height)
scrollView.contentOffset = CGPoint(x: self.view.frame.size.width, y: 0)
var tableView = UITableView(frame: CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height))
tableView.dataSource = self
tableView.registerClass(SnapchatTableViewCell.self, forCellReuseIdentifier: "cell")
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
scrollView.addSubview(tableView)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//TableView DataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 80
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as SnapchatTableViewCell
cell.delegate = self
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.cellScrollView.contentSize = CGSizeMake((2 * cell.frame.size.width), cell.frame.size.height) //This is where the crash occurs, the error tells me cell.cellScrollView is nil
return cell
}
}
..and here is the class that inherits UITableViewCell and is the custom class of the cell in storyboard:
import UIKit
class SnapchatTableViewCell: UITableViewCell, UIScrollViewDelegate {
#IBOutlet var cellScrollView: UIScrollView!
#IBOutlet var colorView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//ScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
}
}
Use the viewWithTag() function in the storyboard instead of using outlets.
Give your cellScrollView a tag for example of 100 then simply call cell.viewWithTag(100) as UIScrollView to access your scroll view. Do the same for all subviews in your cell.

Resources