Swift PickerView with custom tableViewCell.xib - ios

I am messing around with swift and i am stuck in creating an UIPickerView connection with a custom TableViewCell.xib. The functionality i want is the following: when i press the switch button a pickerView appears that lets me select a month which will appear instead of the "Select Month" label. I don't really understand where should i create the outlets.
Cell Xib
Main StoryBoard
class TableViewCell: UITableViewCell {
#IBOutlet weak var leftImage: UIImageView!
#IBOutlet weak var label: UILabel!
#IBOutlet weak var rightImage: UIImageView!
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
}
func commonInit(_ imageName1: String, _ imageName2: String, text: String){
leftImage.image = UIImage(named: imageName1)
rightImage.image = UIImage(named: imageName2)
label.text = text
}
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let textData = ["Select Month"]
let datePicker = UIDatePicker()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "UiTableView"
tableView.delegate = self
tableView.dataSource = self
let nibName = UINib(nibName: "TableViewCell", bundle: nil)
tableView.register(nibName, forCellReuseIdentifier: "tableViewCell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return textData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! TableViewCell
cell.commonInit("facebook", "twitter", text: textData[indexPath.item])
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 170
}
func createDatePicker(){
let toolBar = UIToolbar()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil)
toolBar.setItems([doneButton], animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Open up the Cell Xib file and choose from the Menu, View>Assistand Editor>Show Assistant Editor. Once the Assistant Editor is open you can open the TableViewCell class. Control Drag from the 3 controls in the XIB in Interface builder to the corresponding entry in the file. Once over the entry such as #IBOutlet weak var leftImage: UIImageView!, it will highlight. Release the mouse and the connection will be established.
It is actually a little bit easier to not type the line with the outlet declaration in the class first. In this case, when you control drag from ID you position the mouse over an empty line and a dialog box appears where you can declare the outlet. It creates the connection at the same time.

Related

Table View items are not showing

I am new to iOS development.
I'm trying to display a list of items in my app using UITableView, but the items are not showing:
My View Controller:
class HistoryView: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
let cellReuseIdentifier = "cell"
#IBOutlet weak var noDataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier: "historyCell")
tableView.delegate = self
tableView.dataSource = self
self.noDataLabel.isHidden=true
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "historyCell") as! HistoryTableViewCell
cell.nickname?.text = "name"
return cell
}
}
My Table View Cell:
class HistoryTableViewCell: UITableViewCell {
#IBOutlet weak var nickname: UILabel!
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
}
}
Any suggestions for what's going on?
condition 1:
if you are using prototype cells remove the line
tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier:"historyCell")
and give cell identifier in the storyboard
condition 2:
if you are using xib file then register the cell like below:-
tableView.register(UINib(nibName: "HistoryTableViewCell", bundle: nil), forCellReuseIdentifier: "historyCell")
you need to register cell like this
tb.register(UINib(nibName: "HistoryTableViewCell", bundle: nil), forCellReuseIdentifier: "historyCell")
I saw #IBOutlet weak var nickname: UILabel!
in the class HistoryTableViewCell.
for table cells,
dequeueReusableCell and register, should called in pairs

ImageView not displaying

i'm practising doing a instagram clone, however when I run the app the default images and like label doesn't show up. where am I going.
this is the code for the feed
import UIKit
class Feed: UITableViewCell {
#IBOutlet weak var imageee: UIImageView!
#IBOutlet weak var like: UILabel!
#IBOutlet weak var user: UILabel!
#IBOutlet weak var comment: UILabel!
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
}
#IBAction func likeButton(_ sender: Any) {
}
This is the feedController view controller.
import UIKit
class FeedController: UIViewController ,
UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableV.delegate = self
// tablev.datasource = self
tableV.dataSource = self
}
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(withIdentifier:"cellTable" , for: indexPath) as! Feed
cell.user.text = "testing12"
cell.like.text = "0"
cell.comment.text = "comment"
cell.imageee.image = UIImage(named: "select.png")
return cell
}
}
where am i going wrong?
I can show you one example,
For instance I have the follow ViewController .
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.dataSource = self
tableView.delegate = self
tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
}
}
extension ViewController : UITableViewDelegate , UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
cell.imageView?.image = UIImage(named: "calendar")
return cell
}
}
and this is the cell
import UIKit
class CustomTableViewCell: UITableViewCell {
#IBOutlet weak var customImage: UIImageView!
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
}
}
and this its xib.
check if you add the image in the Assets.xcassets folder

TableViewCell is not clickable with one finger tap, but it is with two fingers

I created a table view and the tableViewCell is not clickable with one finger, but when I try to click the tableViewCell with two fingers the click event takes place. I don't know why this occurres. I created a custom cell in tableView.
InviteVC
import UIKit
class InvitePeopleVC: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {
var nameArray = ["Alwin Lazar", "Ajith Ramesh CR", "Ebrahim KK", "Vishnu Prakash"]
var emailArray = ["alwin#xeoscript.com", "ajith#xeoscript.com", "ebrahim#xeoscript.com", "vishnu#xeoscript.com"]
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var doneImg: UIImageView!
#IBOutlet weak var nameTextFld: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
delegates()
uiModifications()
gestureRecognizers()
}
func delegates() {
tableView.dataSource = self
tableView.delegate = self
nameTextFld.delegate = self
}
func uiModifications() {
nameTextFld.attributedPlaceholder = NSAttributedString(string: "Name or email address", attributes: [NSForegroundColorAttributeName: UIColor.white])
}
func gestureRecognizers() {
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.dismissKeyboard)))
self.doneImg.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.doneImgPressed)))
}
func dismissKeyboard() {
nameTextFld.resignFirstResponder()
}
func doneImgPressed() {
print("done Image tapped")
}
func inviteBtnPressed() {
print("invite button pressed")
}
// UITextFieldDelegate method
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.nameTextFld {
self.nameTextFld.resignFirstResponder()
}
return true
}
// TableView DataSource methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "InviteCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! InviteCell
cell.nameLbl.text = nameArray[indexPath.row]
cell.emailLbl.text = emailArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
// TableView Delegate methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("selected row is \(indexPath.row)")
}
#IBAction func backBtnPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
#InviteCell
import UIKit
class InviteCell: UITableViewCell {
#IBOutlet weak var nameLbl: UILabel!
#IBOutlet weak var emailLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
UIViewController Images
TableView Attributes Inspector
InviteCell Atribute Inspector
In the code above, I'm trying to select a cell with one finger, but the selection does not happen.
Thanks in advance...
A more elegant way of dealing with the tap issue is:
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AppController.dismissKeyboard))
view.addGestureRecognizer(tap)
//this is the KEY of the fix
tap.cancelsTouchesInView = false
This way you can keep your gesture recognizer and still get the table view action in one single tap/selection.
You have the following line in your set up code:
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.dismissKeyboard)))
That sets up a gesture recognizer for your whole view and that would swallow any touches on the main view. If you remove that, you should get the table cell selection working correctly :)
The Tap gesture you have added in the code is causing the issue. Tapgesture recogniser is listening to the user tap actions in the view. The cell select listner is being blocked by the added Tap gesture.
As #Fahim said, if you remove the tap gesture from your code, then cell selection will work smoothly.

Custom cell content doesn't show Swift

I want to create a custom table view. I have an UITableViewController:
class MainListView: UITableViewController{
var invoceList: [InvoceObject] = []
#IBOutlet var tbMain: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(CustomCell.self, forCellReuseIdentifier: "cell")
tbMain.delegate = self
self.tbMain.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.invoceList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.lblBuyerName?.text = self.invoceList[indexPath.row].BUYER_NAME
cell.lblDate?.text = self.invoceList[indexPath.row].CREATED_AT
cell.lblPriceGross?.text = self.invoceList[indexPath.row].PRICE + " " + self.invoceList[indexPath.row].CURRENCY
cell.backgroundColor = UIColor(white: 1, alpha: 0.5)
return cell
}
}
And my UITableViewCell class:
class CustomCell: UITableViewCell {
#IBOutlet weak var lblBuyerName: UILabel!
#IBOutlet weak var lblDate: UILabel!
#IBOutlet weak var lblPriceGross: UILabel!
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
}
}
After build I get an empty cells. I have a number of rows like invoceList.count, but there is no labels and it looks as empty table. What I'm doing wrong?
Since you are using UITableViewController there is an implicit tableView property with connected data source and delegate. You should use that to avoid confusion.
And delete the line self.tableView.register... if you are using prototype cells.
If the cell's contents are defined in a separate xib file, you need to register that, not the class - if you only register the class, the actual labels are not being created because the class itself does not create them.
//Replacing CustomCellNibName with the name of your xib file
tableView.register(UINib.init(nibName: "CustomCellNibName", bundle: nil), forCellReuseIdentifier: "Cell")
If the cell is being created in the storyboard as a prototype cell, you do not need to register it, but just associate the class with your cell in the storyboard file (under the identity inspector tab, Custom Class), and fill in the name you want to use (in this case, "Cell") under the Attributes inspector field Identifier.

Custom UITableViewCell using xib and autolayout doesn`t show correctly in several cells on the top

I used custom UITableViewCell named "SCTableViewCell" and linked with "CustomCell.xib" and loading in "CenterViewController"
and when it runs, several cells on the top looks bad(like follow picture) and, after scroll down screen and up again(bad cells once disappear and appear again) it looks fine
it is custom cell class
SCTableViewCell.swift
class SCTableViewCell: UITableViewCell {
#IBOutlet weak var thumbnailImage : UIImageView!
#IBOutlet weak var titleLabel : UILabel!
#IBOutlet weak var descLabel : UILabel!
func loadItem(#title: String, desc: String, image: UIImage){
titleLabel.text = title
descLabel.text = desc
thumbnailImage.image = image
self.contentView.setTranslatesAutoresizingMaskIntoConstraints(true)
}
override func layoutSubviews() {
}
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
}
}
and CenterViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
//Setting Custom Tableview Cell
self.tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as SCTableViewCell
cell.loadItem(title: title!, desc: desc!, image: pic)
cell.updateConstraints()
return cell
}
console shows nothing....
please help me...
Oh!
I didn`t set up my cell height... ha...ha....
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 160
}
added in CenterViewController.swift and it works

Resources