I recently upgraded my iPhone and Xcode to iOS 8 (from iOS 6) and a UITableView that was previously showing the reorder control on the UITableViewCells (in iOS 6) is no longer showing them until I press the deletion control (red circle) on the left side, at which point the "Delete" button slides over from the right side and the reorder control does appear on that particular UITableViewCell. Below are the relevant methods I am implementing in my UITableViewDataSource. I have set the editing property to YES on the UITableViewController, as well as the UITableView and UITableViewCell in viewDidLoad, but the latter two don't seem to have an effect so I removed them.
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
static NSString *CellIdentifier = #"ContactsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.editingAccessoryType = UITableViewCellAccessoryNone;
//All but the last cell should show the reorder control
if (indexPath.item < contacts.count)
{
cell.textLabel.text = [contacts contactNameAtIndex: indexPath.item];
cell.textLabel.textColor = [UIColor blackColor];
cell.textLabel.font = [UIFont systemFontOfSize: 18];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.showsReorderControl = YES;
}
else
{
cell.textLabel.text = #"Add a contact";
cell.textLabel.textColor = [UIColor grayColor];
cell.textLabel.font = [UIFont systemFontOfSize: 16];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.showsReorderControl = NO;
}
return cell;
}
- (BOOL) tableView: (UITableView *) tableView canMoveRowAtIndexPath: (NSIndexPath *) indexPath
{
return indexPath.item < contacts.count; //All but the last cell can be reordered
}
- (void) tableView: (UITableView *) tableView moveRowAtIndexPath: (NSIndexPath *) fromIndexPath toIndexPath: (NSIndexPath *) toIndexPath
{
[contacts moveContactAtIndex: fromIndexPath.item ToIndex: toIndexPath.item];
}
Thanks,
Vatche
Related
I am developing an app in which, the image of the UIButton in UITableViewCell should change on click and I have done this in a custom cell. Right now, I am able to change the image of the button but it is also changing the image of few other buttons too as I scroll down (as cellForRowAtIndexPath: is called on scrolling).
Here is the code.
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
_cell = (ListTableViewCell *)[self.tblList dequeueReusableCellWithIdentifier:#"listTableViewCell"];
if (_cell == nil) {
_cell = [[ListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"listTableViewCell"];
} else {
_cell.imgIcon.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#",[_arrImages objectAtIndex:indexPath.row]]];
_cell.lblList.text = [NSString stringWithFormat:#"%#",[_arrNames objectAtIndex:indexPath.row]];
_cell.btnList.tag = indexPath.row;
if (_cell.btnList.tag == indexPath.row) {
[_cell.btnList addTarget:self action:#selector(btnPressedMethodCall:) forControlEvents:UIControlEventTouchUpInside];
}
}
return _cell;
}
- (void) btnPressedMethodCall:(UIButton*)sender {
if ([sender isSelected]) {
[sender setImage:[UIImage imageNamed:#"red_image.png"] forState:UIControlStateSelected];
[sender setSelected:NO];
} else {
[sender setImage:[UIImage imageNamed:#"black_image.png"] forState:UIControlStateNormal];
[sender setSelected:YES];
}
}
Could someone please tell how this problem can be solved. Any help is appreciated thanks.
Instead of changing image in button click event. Add selected button indexPath in NSMutableArray and in cellForRow method check NSMutableArray contain current indexPath. if yes than change button image else set normal image like below.
Swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TableViewCell = self.tblVW.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
cell.selectionStyle = .none
cell.btn.tag = indexPath.row
cell.btn.addTarget(self, action: #selector(btnTapped), for: .touchUpInside)
if arrIndexPaths.contains(indexPath) {
cell.btn.setImage(YOUR_BUTTON_SELECTED_IMAGE, for: .normal)
}
else {
cell.btn.setImage(YOUR_BUTTON_DEFAULT_IMAGE, for: .normal)
}
cell.layoutSubviews()
return cell;
}
#IBAction func btnTapped(_ sender: UIButton) {
let selectedIndexPath = NSIndexPath.init(row: sender.tag, section: 0)
arrIndexPaths.add(selectedIndexPath)
self.tblVW.reloadData()
}
If you want to reload only single row than replace self.tblVW.reloadData() with self.tblVW.reloadRows(at: [selectedIndexPath as IndexPath], with: UITableViewRowAnimation.none)
Objective C
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"TableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil] objectAtIndex:0];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.btn.tag = indexPath.row
[cell.btn addTarget:self action:#selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
if ([arrIndexPaths containsObject: indexPath]) {
[cell.btn setImage:YOUR_BUTTON_SELECTED_IMAGE forState:UIControlStateNormal];
}
else {
[cell.btn setImage:YOUR_BUTTON_DEFAULT_IMAGE forState:UIControlStateNormal];
}
[cell layoutSubviews];
return cell;
}
-(IBAction)btnTapped:(UIButton *)sender {
NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
[arrIndexPaths addObject:selectedIndexPath];
[self.tblVW reloadData]; // Reload Whole TableView
//OR
NSArray* indexArray = [NSArray arrayWithObjects:selectedIndexPath, nil];
[self.tblVW reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationNone]; // Reload Single Row
}
I have a UICollectionView inside a UITableViewCell. You may refer the image at here
I would like to reload the collectionView if any update happen.
I have done some research and found this :
how to reload a collectionview that is inside a tableviewcell
Reloading collection view inside a table view cell happens after all cells in table view have been loaded
UICollectionView not updating inside UITableViewCell
I called the #IBOutlet weak var collectionView: UICollectionView! from UITableViewCell to UITableViewController at cellForRowAt.
Here is the code:
var refreshNow: Bool = false
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.allCardCell, for: indexPath) as! AllCardTableViewCell
if refreshNow {
cell.collectionView.reloadData()
refreshNow = false
}
cell.collectionView.collectionViewLayout.invalidateLayout()
return cell
}
If the user click Ok on UIAlertAction :
let alert = UIAlertController(title: "Success", message: "Card successfully added", preferredStyle: .alert)
let action = UIAlertAction(title: "Ok", style: .default) { (action) in
self.refreshNow = true
self.tableView.reloadData()
}
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
The reason why I put the refreshNow is to prevent the apps from lagging and slow. But still did not update if any changes happen.
The problem is the collectionView did not refresh. But when I debug, it was went through the cell.collectionView.reloadData().
The update/changes only happen when I restart the apps. I want it to be so called real-times update.
Any help is really appreciated and many thanks.
Image credit: How to use StoryBoard quick build a collectionView inside UITableViewCell
At end of your update add:
DispatchQueue.main.async() { () -> Void in
self.tableView.reloadData()
}
In your case, you should assign tag to your collection view in order to get access outside the cellForRowAt function.
This is how your function should look like:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.allCardCell, for: indexPath) as! AllCardTableViewCell
cell.collectionView.tag = 1234
return cell
}
and the action will reload it will access the collectionView by using the tag
let action = UIAlertAction(title: "Ok", style: .default) { (action) in
let collectionView = self.tableView.viewWithTag(1234) as! UICollectionView
collectionView.reloadData()
}
Also take note that cellForRowAt will keep reload the content based what you added inside it every time the cell appear. So, keep updating your data outside the cellForRowAt function.
Because you reused UITableViewCell so you must alway reload your UICollectionView. If you use refreshNow to reload UICollectionView, at the cell have refreshNow = false, UICollectionView will display like cell that it 's reused => wrong
Udate rep:
See , in picture uitableviewcell 1 will reuse at index 6. If you not reload content of cell (reload collectionview) it will display like uitableviewcell 1 at index 0
#import "AddPhotoViewController.h"
#import "PhotoTableViewCell.h"
#import "ShareTableViewCell.h"
#interface AddPhotoViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tblView;
#property (strong,nonatomic)NSMutableArray *arrImages,*arrIndexPath,*selectImages;
#end
#pragma mark - TableViewDelegate&DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *returnCell;
static NSString *cellIdentifier = #"CellOne";
static NSString *cellIdentifierTwo = #"CellTwo";
static NSString *cellIdentifierThree = #"CellThree";
if (indexPath.row == 0) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
returnCell = cell;
} else if (indexPath.row == 1){
ShareTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifierTwo forIndexPath:indexPath];
cell.viewMood.layer.cornerRadius = 5;
cell.viewPeople.layer.cornerRadius = 5;
[cell.viewMood layer].borderWidth = 1;
[cell.viewMood layer].borderColor = [UIColor colorWithRed:241.0/255.0 green:143.0/255.0 blue:48.0/255.0 alpha:1].CGColor;
[cell.viewPeople layer].borderWidth = 1;
[cell.viewPeople layer].borderColor = [UIColor colorWithRed:241.0/255.0 green:143.0/255.0 blue:48.0/255.0 alpha:1].CGColor;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
returnCell = cell;
}else if (indexPath.row == 2){
PhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifierThree forIndexPath:indexPath];
cell.collView.dataSource = self;
cell.collView.delegate = self;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
returnCell = cell;
}
return returnCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;
}
#pragma mark- UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
[_arrImages addObject:chosenImage];
PhotoTableViewCell *cell = [self.tblView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
[cell.collView reloadData];
[picker dismissViewControllerAnimated:YES completion:^{
}];
}
#pragma mark - CollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [_arrImages count];
}
- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"CellCollection";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UIImageView *imgView = [(UIImageView*)[cell contentView] viewWithTag:100];
UIImageView *imgViewTick = [(UIImageView*)[cell contentView] viewWithTag:200];
UIView *view = [(UIView*)[cell contentView] viewWithTag:300];
if (indexPath.row == 0){
imgViewTick.hidden = YES;
view.hidden = YES;
}
if ([_arrIndexPath containsObject:indexPath]) {
[_selectImages removeAllObjects];
view.hidden = NO;
view.alpha = 0.4;
imgViewTick.hidden = NO;
imgView.image = [_arrImages objectAtIndex:indexPath.row];
[_selectImages addObject:[_arrImages objectAtIndex:indexPath.row]];
NSLog(#"Pick images:%#",_selectImages);
}else{
view.hidden = YES;
imgViewTick.hidden = YES;
imgView.image = [_arrImages objectAtIndex:indexPath.row];
}
return cell;
}
This question already has answers here:
Select multiple rows in UITableview [duplicate]
(5 answers)
Closed 6 years ago.
I have list of states in UITableView.Now i want to select multiple row of UITableView and wanna get this selected row values in one array.how can i get this?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//NSMutableArray *arrData =[statearray objectAtIndex:indexPath.row];
NSLog(#"arrdata>>%#",statearray);
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [statearray objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}
You can call tableview.indexPathForSelectedRows. This will output an array with the indexpaths for all selected rows in your tableview!
This is how your code would look like in swift 3:
var values : [String] = []
let selected_indexPaths = tableView.indexPathsForSelectedRows
for indexPath in selected_indexPaths! {
let cell = tableView.cellForRow(at: indexPath)
values.append((cell?.textLabel?.text)!)
}
After running this code the values of all selected cells should be in the values array.
you can keep track of selected cells with below way
var selectedCells: [UITableViewCell] = []
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedCells.append(tableView.cellForRow(at: indexPath)!)
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let deselectedRow = tableView.cellForRow(at: indexPath)
if(selectedCells.contains(deselectedRow!)){
let indx = selectedCells.index(of: deselectedRow!)
selectedCells.remove(at: indx!)
}
}
Idea is to maintain array of selected cells when cell selection happens and remove cell once deselection is done
Best way is to get selected indexpaths using method
tableView.indexPathsForSelectedRows
you can get the data out in an array
var oldArray: [NSIndexPath] = [NSIndexPath.init(row: 0, section: 0), NSIndexPath.init(row: 1, section: 0), NSIndexPath.init(row: 2, section: 0), NSIndexPath.init(row: 3, section: 0)]
var newArray: [Int] = oldArray.flatMap { ($0.row) }
Like if we have array in form of oldArray, We can get only rows using flatMap.
There is default method of tableview,
self.tableView.indexPathsForSelectedRows
Which gives you an array of selected indexpaths. But you need to also set property of tableview
self.tableView.allowsMultipleSelection = true
If want back selcted rows to track,
NSArray *selectedRowsArray = [yourTableViewName indexPathsForSelectedRows];
Answer updated
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//the below code will allow multiple selection
if ([yourMutableArray containsObject:indexPath])
{
[yourMutableArray removeObject:indexPath];
}
else
{
[yourMutableArray addObject:indexPath];
}
[yourTableView reloadData];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
if ([yourMutableArray containsObject:indexPath])
{
//Do here what you wants
if (contentArray.count > 0) {
NSDictionary *dictObje = [contentArray objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#",[dictObje objectForKey:#"name"]];
}
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
//Do here what you wants
if (contentArray.count > 0) {
NSDictionary *dictObje = [contentArray objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#",[dictObje objectForKey:#"name"]];
}
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
I am using tableView to display some information which is just four line of information. And i want to assign respective information to each row.
Like how shown in the below image there are four rows, same as in the image so i am using tableView for that. Here my problem is that i have created four cells but don't know how should i use label in specific cell and show the info.
and also if the value is null that row should not be there means if two values among four are null then only two rows having values should be there in tableView. How can i achieve this. Till now i am only able to show one row information only.
- (NSArray *)myTableViewCells
{
if (!_myTableViewCells)
{
_myTableViewCells = #[
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil],
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil],
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil],
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]
];
}
return _myTableViewCells;
}
if([managedObject valueForKey:#"personality_company_master_values"] != nil)
{
[_displayValues addObject:[NSString stringWithFormat:#"Personality %#",[managedObject valueForKey:#"personality_company_master_values"]]];
}
if([managedObject valueForKey:#"video_tag"] != nil)
{
[_displayValues addObject:[NSString stringWithFormat:#"Tag %#",[managedObject valueForKey:#"video_tag"]]];
}
if([managedObject valueForKey:#"industry_master_values"] != nil)
{
[_displayValues addObject:[NSString stringWithFormat:#"Industry %#",[managedObject valueForKey:#"industry_master_values"]]];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.myTableViewCells.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = self.myTableViewCells[indexPath.row];
// NSManagedObject *managedObject = [self.devices lastObject];
cell.backgroundColor = [self colorFromHexString:#"#014455"];
cell.textLabel.text = _displayValues[indexPath.row];
cell.textLabel.backgroundColor = [self colorFromHexString:#"#014455"];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.font=[UIFont systemFontOfSize:14.0];
// UILabel *lbl=(UILabel*)[cell viewWithTag:900];
// [lbl setText:[managedObject valueForKey:#"personality_company_master_values"]];
// lbl.textColor=[UIColor blackColor];
return cell;
}
Get the value you want display in an array.
Something like this
#property (monatomic, strong)NSMuatableArray *displayValues;
-(void)viewDidLoad
{
self.displayValues = [[NSMutableArray alloc]init];
NSManagedObject *managedObject = [self.devices lastObject];
if([managedObject valueForKey:#"personality_company_master_values"] != nil)
{
[self.displayValues addObject:[managedObject valueForKey:#"personality_company_master_values"]];
}
if([managedObject valueForKey:#"company_master_values"] != nil)
{
[self.displayValues addObject:[managedObject valueForKey:#"company_master_values"]];
}
if([managedObject valueForKey:#"tag_master_values"] != nil)
{
[self.displayValues addObject:[managedObject valueForKey:#"tag_master_values"]];
}
}
- (NSArray *)myTableViewCells
{
if (!_myTableViewCells)
{
_myTableViewCells = #[
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil],
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil],
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil],
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]
];
}
return _myTableViewCells;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.displayValues.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = self.myTableViewCells[indexPath.row];
// NSManagedObject *managedObject = [self.devices lastObject];
//cell.textLabel.text = [NSString stringWithFormat:#"%#",[managedObject valueForKey:#"personality_company_master_values"]];
cell.textLabel.text = self.displayValues[indexPath.row];
//not getting have to do this way or any other way please help
// secondLabel.text = [NSString stringWithFormat:#"%#",[managedObject valueForKey:#"company_master_values"]];
// thirdLabel.text = [NSString stringWithFormat:#"%#",[managedObject valueForKey:#"tag_master_values"]];
return cell;
}
I'm afraid you're doing several things wrong, starting with preallocating an array of cells. Tableviews don't work like that, you provide cells on demand and populate them with values from your data model. When you want to remove a cell update your data model then call reloadData(). Here's a simple example:
import UIKit
class MyCell: UITableViewCell {
var row: Int = -1 // serves no purpose but to show how you might subclass a UITableViewCell
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var dataModel = [
"Hello", "World,", "this", "is", "a", "tableview"
]
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
var frame = view.bounds
let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.height
frame.origin.y += statusBarHeight
frame.size.height -= statusBarHeight
tableView = UITableView(frame: frame, style: .Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(MyCell.self, forCellReuseIdentifier: "mycell")
view.addSubview(tableView)
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataModel.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("mycell") as! MyCell
let row = indexPath.row
cell.row = row // there is no point in doing this other than to show it as an example
cell.textLabel!.text = dataModel[row]
return cell
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
dataModel.removeAtIndex(indexPath.row)
tableView.reloadData()
}
}
EDIT: Here's an objective c version
////////////////////////////
/// Objective C Version //
////////////////////////////
#import "ViewController.h"
#interface MyCell: UITableViewCell
#property(assign) NSInteger row; // serves no purpose but to show how you might subclass a UITableViewCell
#end
#implementation MyCell #end
#interface ViewController() <UITableViewDataSource, UITableViewDelegate>
#property NSMutableArray *dataModel;
#property UITableView *tableView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_dataModel = [NSMutableArray arrayWithArray: #[#"Hello", #"World,", #"this", #"is", #"a", #"tableview"]];
CGRect frame = self.view.bounds;
CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
frame.origin.y += statusBarHeight;
frame.size.height -= statusBarHeight;
_tableView = [[UITableView alloc] initWithFrame: frame style: UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[_tableView registerClass: [MyCell class] forCellReuseIdentifier: #"mycell"];
[self.view addSubview: _tableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataModel.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = (MyCell *) [tableView dequeueReusableCellWithIdentifier: #"mycell"];
NSInteger row = indexPath.row;
cell.row = row; // there is no point in doing this other than to show it as an example
cell.textLabel.text = _dataModel[row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[_dataModel removeObjectAtIndex: indexPath.row];
[_tableView reloadData];
}
#end
You dont need to create a fixed amount of cells this is not an efficient solution to the problem. You should create NSMutableDictionary and save the data like this:
NSMutableArray *data = [NSMutableDictionary dictionary];
[data setValue:#"Vijayakanth" forKey:#"Personality"];
Now in the table view delegate you can return the keys count for noOfRowsInSection and in cellForRowAtIndexPath you can get the key from dictionary get the value w.r.t that key and assign the values to your cell. In your case:
Key: Personality (which is shown on the left side)
Value: Vijayakanth (which is shown on the right side)
Hope you understand the point.
I have a table view and now I'm initialising the table like,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [arr count]+1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arr count]+1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
if (row == 0)
{
UITableViewCell *cell = [[UITableViewCell alloc] init];
return cell;
}
else
{
static NSString *CellIdentifier = #"moduleCell";
MyTableViewCell *cell = (MyTableViewCell*)[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MyTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.backgroundColor = [UIColor clearColor];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#""]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
current = [arr objectAtIndex:indexPath.row-1];
[cell setCellDetails:arr WithIndex:row-1 withParentView:self];
return cell;
}
}
When I'm doing this data repeating in my tableview. Before I do this, I did,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
This is working but I need to set section headers like titles. So is there a way to set section headers without repeating data?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 0){//for first section
}else if(indexPath.section == 1){//for second section
}
}
You need to implement this method:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (section==0) {
return "name";
}else{
//
}
}
You need to keep heading in Array. So, you can avoid hardcoded in the delegate method.
NSArray *heading=#[#"Today",#"Yesterday",#"Tomorrow"];
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *heading = [heading objectAtIndex:section]; //
return heading;
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var cstmView:UIView!
let lbl:UILabel
cstmView = UIView()
cstmView.frame = CGRectMake(0,0,tableView.contentSize.width,70.0)
let logo:UIImageView = UIImageView();
logo.image = UIImage(named: "logo_with_lightGrayColor")
logo.frame = CGRectMake(8.0,10.0,200.0,60.0)
lbl = UILabel()
lbl.frame = CGRectMake(8.0,80.0,200.0,20.0)
lbl.text = "USER NAME"
lbl.textColor = UIColor.whiteColor()
lbl.font = UIFont.systemFontOfSize(15.0)
cstmView .addSubview(logo)
cstmView.addSubview(lbl)
return cstmView;
}
You should implement custom header for tableview.