Swift 3 - How to Insert Tableviewcells from Another View

Swift 3 - How do I insert TableViewCells from another view?

The problem is this expression you keep trying to use:

MyTableView()

That creates a completely new and separate table view controller. But that obviously is not what you want to do. You want to talk to the existing table view controller, the one that is, as you say, another tab in the tab bar controller.

For example, if MyTableView is the first tab and OtherViewController is the second tab, then OtherViewController might say:

self.tabBarController!.viewControllers![0] as! MyTableView

...as a way of getting a reference to the existing table view controller.

How to insert new cell into UITableView in Swift

Use beginUpdates and endUpdates to insert a new cell when the button clicked.

As @vadian said in comment, begin/endUpdates has no effect for a single insert/delete/move operation

First of all, append data in your tableview array

Yourarray.append([labeltext])  

Then update your table and insert a new row

// Update Table Data
tblname.beginUpdates()
tblname.insertRowsAtIndexPaths([
NSIndexPath(forRow: Yourarray.count-1, inSection: 0)], withRowAnimation: .Automatic)
tblname.endUpdates()

This inserts cell and doesn't need to reload the whole table but if you get any problem with this, you can also use tableview.reloadData()


Swift 3.0

tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: yourArray.count-1, section: 0)], with: .automatic)
tableView.endUpdates()

Objective-C

[self.tblname beginUpdates];
NSArray *arr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:Yourarray.count-1 inSection:0]];
[self.tblname insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tblname endUpdates];

How to insert a new cell in between UITableViewCell in Swift

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
(...)
tableView.insertRows(at: [IndexPaths], with: .top)
}

How can I update table view from another view controller with out segues in swift 3?

You can use NotificationCenter like this:

class FirstViewController : UIViewController {

func someAction (){
NotificationCenter.default.post(name: Notification.Name("UPDATED_DATA"), object: nil) // post updated data
}

}

class TableViewController : UITableViewController {
override func viewDidLoad() {

}

override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self,
selector: #selector(updated_data),
name:Notification.Name("UPDATED_DATA"),
object: nil)//register for notification
}

override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
}

func updated_data(notification:Notification) -> Void{
tableView.reloadData() // update data here
}
}

TableViewCell squeezes subviews when adding accessory in Swift 3

How are your trailing constraints set for those labels? Setting them to be = 8 to leading edge of your imageView will allow them to stretch all the way to 8 points away from the imageView. Also keep in mind if you are already doing this, and setting the imageView's view.frame.width = 0 if the check mark isn't going to be present, would also cause the difference in the views.

You could set the imageView.isHidden = true to keep the views looking the same.

Is it possible to add UITableView within a UITableViewCell

yes it is possible, I added the UITableVIew within the UITableView cell
.. :)

no need to add tableview cell in xib file - just subclass the UITableviewCell and use the code below, a cell will be created programatically.

//in your main TableView 

#import "ViewController.h"
#import "CustomCell.h"
@interface ViewController ()<UITableViewDataSource , UITableViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)dealloc
{
[_aTV release];
[super dealloc];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = [self.aTV dequeueReusableCellWithIdentifier:@"Cell"];
if(cell == nil)
{
cell = [[[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"]autorelease];
}

cell.dataAraay = [NSMutableArray arrayWithObjects:@"subMenu->1",@"subMenu->2",@"subMenu->3",@"subMenu->4",@"subMenu->5", nil];
return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 150;
}

//in your custom tableview cell
// .m file
#import "CustomCell.h"

@implementation CustomCell
@synthesize dataAraay; //array to hold submenu data

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
self.frame = CGRectMake(0, 0, 300, 50);
UITableView *subMenuTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain]; //create tableview a

subMenuTableView.tag = 100;
subMenuTableView.delegate = self;
subMenuTableView.dataSource = self;
[self addSubview:subMenuTableView]; // add it cell
[subMenuTableView release]; // for without ARC
}
return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];

// Configure the view for the selected state
}

-(void)layoutSubviews
{
[super layoutSubviews];
UITableView *subMenuTableView =(UITableView *) [self viewWithTag:100];
subMenuTableView.frame = CGRectMake(0.2, 0.3, self.bounds.size.width-5, self.bounds.size.height-5);//set the frames for tableview

}

//manage datasource and delegate for submenu tableview
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return dataAraay.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
if(cell == nil)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"]autorelease];
}
cell.textLabel.text = [self.dataAraay objectAtIndex:indexPath.row];

return cell;

}

@end


Swift version
Create a single view project add tableview inside storyboard and set up its datasource and delegate

Paste code below to ViewController.swift

  import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

override func viewDidLoad() {
super.viewDidLoad()
// 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.
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3;
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? CustomCell
if cell == nil {
cell = CustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
cell?.dataArr = ["subMenu->1","subMenu->2","subMenu->3","subMenu->4","subMenu->5"]
return cell!
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 150.0
}
}

create a new file CustomCell.swift which is the subclass of UITableViewCell and do not select with xib this file is without .xib file table and its cell will be created programatically as in objective-c code.

Paste code below to CustomCell.swift

  import UIKit

class CustomCell: UITableViewCell,UITableViewDataSource,UITableViewDelegate {

var dataArr:[String] = []
var subMenuTable:UITableView?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style , reuseIdentifier: reuseIdentifier)
setUpTable()
}

required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
setUpTable()
}

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setUpTable()
}

func setUpTable(){
subMenuTable = UITableView(frame: CGRectZero, style:UITableViewStyle.Plain)
subMenuTable?.delegate = self
subMenuTable?.dataSource = self
self.addSubview(subMenuTable!)
}

override func layoutSubviews() {
super.layoutSubviews()
subMenuTable?.frame = CGRectMake(0.2, 0.3, self.bounds.size.width-5, self.bounds.size.height-5)
}

override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cellID")

if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cellID")
}

cell?.textLabel?.text = dataArr[indexPath.row]

return cell!
}
}


Related Topics



Leave a reply



Submit