UITextView in UITablecell fill TextView text on custom cell - ios

I am working with Custom UITableCell and dynamic UITextView in my application.
I have one issue regarding ios7 which i explain as follows:
i have created one view on UITable Cell Custom Button click like as follows. this view contains UITextView to input the text and fell it on cell later as on comment table.
// For iOS7
UITableView *table = nil;
if([CommonFunction isiOS7]){
table = (UITableView*)[[[[[sender superview] superview] superview] superview] superview];
indexPath=[[NSIndexPath alloc] init];//
indexPath = [table indexPathForCell:self];
}
else {
indexPath=[[NSIndexPath alloc] init];//
indexPath = [(UITableView *)self.superview indexPathForCell: self];
}
NSLog(#"indexPath:%#",indexPath);
if (appDelegate.dictLogedInUserData) {
//[(UITableView*)self.superview scrollToRowAtIndexPath:[(UITableView *)self.superview indexPathForCell:self] atScrollPosition:UITableViewScrollPositionTop animated:YES];
[table scrollToRowAtIndexPath:[table indexPathForCell:self] atScrollPosition:UITableViewScrollPositionTop animated:YES];
TextInputView *txtInput = [[TextInputView alloc] init];
txtInput.delegate=self;
if ([btnAddComment.titleLabel.text length]>0) {
if (![btnAddComment.titleLabel.text isEqualToString:#"Add Comment"]) {
txtInput.txtComments.text = btnAddComment.titleLabel.text;
}
}
txtInput.backgroundColor = [UIColor clearColor];
//[(UITableView*)[self superview] setScrollEnabled:NO];
[table setScrollEnabled:NO];
[self addSubview:txtInput];
[self bringSubviewToFront:txtInput];
}
When use enter some text i need to fill this UITextView text value to my UITableCell CustomView which code is as follows,This is delegate method:
//InputText Delegates
- (void)didFinishInput:(NSString *)inputedText {
btnAddComment.titleLabel.text = inputedText;
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:indexPath, #"indexPath",
[NSString stringWithFormat:#"%#",inputedText],#"commentText",nil];
NSLog(#"dict:%#",dict);
topic *t = [appDelegate.arrayTopicsData objectAtIndex:indexPath.row];
t.user_comment = inputedText;
[appDelegate.arrayTopicsData replaceObjectAtIndex:indexPath.row withObject:t];
[self LoadDataForIndex:indexPath];
[delegate didAddComment:dict];
[(UITableView*)[self superview] setScrollEnabled:YES];
if ([inputedText length]<=0) {
btnAddComment.titleLabel.text = #"Add Comment";
}
}
In the above code it always crash when i enter text on UITextView and press Done button of key board. it gives EXE-BAD-Access on indexPath in iOS7.
Please help me how to get Indexpath on UITextView delegate method when i am passing NSString to the Method.
Please help me.

Related

UISegment Control in UITableView Prototype cell, when value is changed in Segment control the scroll is moved to top

I have a screen, where we are displaying questions with YES or NO. For Yes Or No we have used UISegment Control.
When a value is changes in the UISegment Control the scroll is moved to Top of the screen, when we have more questions and when we select last or but last as shown in the image.
Below is the code used to render the controls.
Link to the videos how the output looks https://imgur.com/nvn1Exw .
Please help me how can i remove the scroll movement on selection of new value in segment control.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return timeOutQuestions.count;
}
- (UITableViewCell* )tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
static NSString* questionTableIdentifier=#"SegmentCell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier: questionTableIdentifier];
if(cell == nil){
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:questionTableIdentifier];
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
}
cell.separatorInset = UIEdgeInsetsMake(0.0 , cell.bounds.size.width , 0.0, -cell.bounds.size.width);
Question* currentQuestion=[[shared getQuestions:questionSet] objectAtIndex:indexPath.row];
#try{
UISegmentedControl *segment = [[cell.contentView subviews] objectAtIndex:0];
segment.selectedSegmentIndex = [[questionSegmentControl objectAtIndex:indexPath.row] integerValue];
[segment addTarget:self action:#selector(segmentSwitch:) forControlEvents:UIControlEventValueChanged];
UILabel *label = [[cell.contentView subviews] objectAtIndex:1];
label.text = currentQuestion.questionText;
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}#catch(NSException* ex){
NSLog(#"%#",ex.reason);
}
if(changeOffSet && indexChangedValue.row > 2){
[self.questionTableView setContentOffset:tableContentOffSet animated:NO];
[UIView setAnimationsEnabled:true];
changeOffSet = false;
}
return cell;
}
- (IBAction)segmentSwitch:(UISegmentedControl *)sender {
NSInteger selectedSegment = sender.selectedSegmentIndex;
CGPoint senderOriginInTableView = [questionTableView convertPoint:CGPointZero fromView:sender];
NSIndexPath *indexPath = [questionTableView indexPathForRowAtPoint:senderOriginInTableView];
indexChangedValue = indexPath;
tableContentOffSet = self.questionTableView.contentOffset;
[UIView setAnimationsEnabled:false];
changeOffSet = true;
}
https://imgur.com/nvn1Exw
I think you are doing the scrolling programatically with this
[self.questionTableView setContentOffset:tableContentOffSet animated:NO];
I think you need to rework it a bit. Stop changing the content offset and see how it goes. Also, maybe you need to get rid of this line
[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
which I think also interferes with the scrolling.

TablewView Cell all cell in the same row

No storyboard involve in this project
The most problematic part i cant figure out where to solve this.
Im Using SDK.
_msgTableView = [[UITableView alloc] init];
_msgTableView.backgroundColor = [UIColor blackColor];
_msgTableView.delegate = self;
_msgTableView.dataSource = self;
_msgTableView.separatorInset = UIEdgeInsetsZero;
_msgTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
_msgTableView.showsVerticalScrollIndicator = NO;
[self.view addSubview:_msgTableView];
this function are called on NSNotification
CGRect moveToRect = CGRectMake(-(msgFrame.origin.x+ msgFrame.size.width), msgFrame.origin.y, msgFrame.size.width, msgFrame.size.height);
[_msgTableView setFrame:moveToRect];
this is called in extended view
[_msgTableView sizeWith:CGSizeMake(screenW, 250)];
[_msgTableView layoutAbove:_bottomView margin:kDefaultMargin];
this is called when new message notify by Notification
[_msgDatas addObject:msg];
if (_msgDatas.count >= 500)
{
NSRange range = NSMakeRange(_msgDatas.count - 100, 100);//只保留最新的100条消息
NSArray *temp = [_msgDatas subarrayWithRange:range];
[_msgDatas removeAllObjects];
[_msgDatas addObjectsFromArray:temp];
[_msgTableView reloadData];
}
else
{
[_msgTableView beginUpdates];
NSIndexPath *index = [NSIndexPath indexPathForRow:_msgDatas.count - 1 inSection:0];
[_msgTableView insertRowsAtIndexPaths:#[index] withRowAnimation:UITableViewRowAnimationAutomatic];
[_msgTableView endUpdates];
}
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_msgDatas.count-1 inSection:0];
if (indexPath.row < [_msgTableView numberOfRowsInSection:0])
{
[_msgTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
this is the Cell For row at function
MsgTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"LiveTextMessageCell"];
if (cell == nil)
{
cell = [[MsgTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"LiveTextMessageCell"];
}
id msg = _msgDatas[indexPath.row];
if ([msg isKindOfClass:[ILVLiveTextMessage class]])
{
ILVLiveTextMessage *textMsg = (ILVLiveTextMessage *)msg;
[cell configMsg:textMsg.sendId ? textMsg.sendId : [[ILiveLoginManager getInstance] getLoginId] msg:textMsg.text];
}
if ([msg isKindOfClass:[ILVLiveCustomMessage class]])
{
ILVLiveCustomMessage *customMsg = (ILVLiveCustomMessage *)msg;
[cell configTips:customMsg.sendId];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
this is the ConfigWith function
CGFloat selfW = [UIScreen mainScreen].bounds.size.width ;
CGFloat selfH = 30;
UIFont *msgFont = [UIFont fontWithName:#"Superclarendon" size:12];//Helvetica-Bold
_nickname = profile.nickname;
NSString *showInfo = [NSString stringWithFormat:#"%#: %#",profile.nickname, text];
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:showInfo];
[attrStr addAttribute:NSForegroundColorAttributeName value:kColorGreen range:NSMakeRange(0, profile.nickname.length+1)];//+1是因为有个冒号
[attrStr addAttribute:NSForegroundColorAttributeName value:kColorWhite range:NSMakeRange(profile.nickname.length+1, text.length+1)];//+1是因为有个空格
[attrStr addAttribute:NSFontAttributeName value:msgFont range:NSMakeRange(0, showInfo.length)];//加粗
_msgLabel.attributedText = attrStr;
CGSize labelsize = [self textHeightSize:showInfo maxSize:CGSizeMake(selfW - kDefaultMargin*2, selfH * 3) textFont:msgFont];
[_msgLabel setFrame:CGRectMake(_msgLabel.frame.origin.x, _msgLabel.frame.origin.y, labelsize.width + kDefaultMargin, labelsize.height)];
[self setFrame:CGRectMake(0, 0, selfW, labelsize.height)];
_height = labelsize.height;
_msgLabel.hidden = NO;
_tipsLabel.hidden = YES;
As per my understanding when a new message notification has come, you are not maintaining the height of the cells according to the data. Hence they seem to be overlapped.
Now you have to maintain the height of the new notification, And the data is obtained should be added to your main array(data source). And hence can be easily coordinated.and cells are not get overlapped.
For maintaining the height of the cells, use "heightForRowAtIndexPath "delegate functions of the table view and Maintain the height of a particular cell accordingly.
And one more thing, please be sure that single message will be in the single cell. This will manage accordingly.
Please make sure that a single message was loaded by a single cell,and the height of cell is correct. It looks like you created lots of UILabels in the same cell.
Try using visual constraints instead of setFrame may help!
I found the solution.
i create a nib file as an extension to tableview cell and i register as nib
but im accepting #mayanksengar answer for giving me good insight
I just created a xib file and .h and .m
register xib to table view
[_msgTableView registerNib:[UINib nibWithNibName:#"customCell2" bundle:nil] forCellReuseIdentifier:#"customCell2"];
finally used it
NSString *cellIdentifier = #"customCell2";
customCell2 *cell= [_msgTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell){
[_msgTableView registerNib:[UINib nibWithNibName:#"customCell2" bundle:nil] forCellReuseIdentifier:#"customCell2"];
}

how to change the textfield value when the button is clicked in uitableviewcell iOS

I'm developing a shopping app, in which i'm implementing a shopping cart. In my app, i need to increase the product quantity when the plus button is clicked and reduce the product quantity when the minus button is clicked. Here my problem is, when i click the plus button, all text field value is changing in the tableviewcell. Help me,below is
plus button action method
-(IBAction)plusBtn:(UIButton*)plus
{
[self.tbleView beginUpdates];
UITableViewCell *clickedCell = (UITableViewCell *)[[plus superview] superview];
NSIndexPath *clickedButtonIndexPath = [self.tbleView indexPathForCell:clickedCell];
plus.tag = clickedButtonIndexPath.row;
quantity.tag = clickedButtonIndexPath.row;
_curr =_curr+1;
quantity.text = [NSString stringWithFormat:#"%d",_curr];
[self.tbleView endUpdates];
[self.tbleView reloadData];
}
like this
getting..
can u check this functionality. it will useful for you. i hope it.
- (void)viewDidLoad
{
[super viewDidLoad];
quantity =[NSMutableArray new];
occu_list = [[NSArray alloc] initWithObjects:#"Occupation", #"two", #"three", #"four", #"five", #"six", #"seven", #"eight", nil];
for(int i=0;i<[occu_list count];i++)
{
[quantity addObject:#"0"];
}
click_textView=[[UIView alloc]init];
click_textView.frame=self.view.frame;
[self.view addSubview:click_textView];
[self tableviewone];
}
-(void)tableviewone
{
tbl_view = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
tbl_view.delegate = self;
tbl_view.dataSource = self;
tbl_view.backgroundColor = [UIColor whiteColor];
tbl_view.layer.borderColor=[[UIColor orangeColor]CGColor];
tbl_view.layer.borderWidth=2.0f;
tbl_view.layer.cornerRadius=5.0f;
tbl_view.layer.masksToBounds=YES;
[click_textView addSubview:tbl_view];
}
-(IBAction)check_btn_action:(id)sender
{
UIButton *btntag=(UIButton*)sender;
NSLog(#"%li",(long)btntag.tag);
NSLog(#"%#",[quantity objectAtIndex:btntag.tag]);
int ad=[[quantity objectAtIndex:btntag.tag]integerValue];
ad=ad+1;
[quantity removeObjectAtIndex:btntag.tag];
[quantity insertObject:[NSString stringWithFormat:#"%i",ad] atIndex:btntag.tag];
[tbl_view reloadData];
}
Write action method for your button and then inside that just use this one line of code for setting your value to the textfield:-
self.yourTxtFld.text=#"yourString"
Don`t write the Button action in ViewController,
write it in the CustomCell class.
example:
in the CustomCell.m
- (IBAction)plusButtonDidClicked:(UIButton *)sender {
int i = [self.textField.text intValue];
i++;
self.textField.text = [NSString stringWithFormat:#"%d", i];
}
Then back to the ViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
return cell;
}
It will be work well.
-(IBAction)plusBtn:(UIButton*)plus
{
UITableViewCell *clickedCell = (UITableViewCell *)[[plus superview] superview];
_curr=_curr+1;
UITextField *qty = (UITextField *) [clickedCell viewWithTag:90];
qty.text=[NSString stringWithFormat:#"%d",_curr];
}

Tableview cell with textfields and button

I have a tableviewcell that has two text fields and a button.
The idea is that you fill in the text field, but the button will bring up another viewcontroller that has some sort of calculator.
My problem comes with bringing the value back into the right cell and textfield.
I get at the button click with this in the Configure cell;
[cell setDidTapButtonBlock:^(id sender) {
[self countNotes:cashoutLine.cashCurrency cell:cell];
}];
This calls this extract of code;
-(void)countNotes:(Currency *)cashCurrency cell:(PouchEntryViewCell *)cell
{
NotesCountViewController *notesCountVC = [[NotesCountViewController alloc] init];
notesCountVC.noteCurrency = cashCurrency;
notesCountVC.notesDelegate = self;
notesCountVC.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:notesCountVC animated:YES completion:nil];
}
All good and the new viewcontroller shows up.
I do the work there and pass back the total using delegate. It arrives happily in the first view controller, but then I'm stuck.
How can I get it to populate the correct cell?
Assuming you're presenting the calculator from the ViewController that acts as the UITableViewDataSource delegate, you can find the correct cell to update the textfield by creating a NSIndexPath property in your NotesCountViewController. Before you present the view controller, set the property. When it is dismissed, pass the NSIndexPath back to your UITableViewDataSource viewController, and find the correct cell with that.
-(void)countNotes:(Currency *)cashCurrency cell:(PouchEntryViewCell *)cell atIndex:(NSIndexPath *)indexPath
{
NotesCountViewController *notesCountVC = [[NotesCountViewController alloc] init];
notesCountVC.noteCurrency = cashCurrency;
notesCountVC.cellIndexPath = indexPath;
notesCountVC.notesDelegate = self;
notesCountVC.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:notesCountVC animated:YES completion:nil];
}
Then get the cell in the Delegate callback with
PouchEntryViewCell *cell = (PouchEntryViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
cell.textField.text = #"New Text";
In NotesCountViewController
- (id) initWithIndexPath:(NSIndexPath *) indexPath {
self = [super init];
if (self) {
self.indexPath = indexPath;
}
return self;
}
Declare this in your .h and also add an indexPath property.. Then just add the self.indexPath in your delegate call back.
To call it just do:
NotesCountViewController *notesCountViewController = [[NotesCountViewController alloc] initWithIndexPath:[self.tableView indexPathForCell:cell];
Then to retrieve the cell in the del callback:
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

Get UITableViewCell of UIButton?

I'm trying to perform a segue using a UIButton, which is located within in a custom UITableViewCell class called GFHomeCell.
The GFHomeCell has a postID property, which I want to send in the prepare for segue. I set up a method to run when the button is pressed; however, in the button-pressed method, I need the sender to be a GFHomeCell(or at least that's what I assume).
Does anyone have any ideas how I can do that? Here is my code
My cellForRowAtIndexPath:
GFHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:#"newsfeedCell" forIndexPath:indexPath];
NSDictionary *rootObject = self.posts[indexPath.row];
NSDictionary *post = rootObject[#"post"];
NSDictionary *group = post[#"group"];
NSString *groupName = group[#"name"];
cell.actionLabel.text = [NSString stringWithFormat:#"New post trending on %#", groupName];
cell.descriptionLabel.text = post[#"body"];
cell.descriptionLabel.numberOfLines = 0;
cell.descriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.likesLabel.text = [NSString stringWithFormat:#"%#", post[#"likes"]];
cell.postId = post[#"id"];
cell.groupName = group[#"name"];
cell.postBody = post[#"body"];
cell.likeButton.tag = indexPath.row;
[cell.likeButton addTarget:self action:#selector(likeButtonClick:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];
[cell.commentButton addTarget:self action:#selector(commentButtonClick:) forControlEvents:(UIControlEvents)UIControlEventTouchDown];
NSString *urlString = [NSString stringWithFormat:#"%s/%#", kBaseURL, #"images/"];
NSURL *url = [NSURL URLWithString:urlString];
[cell.imageView setImageWithURL:url
placeholderImage:[UIImage imageNamed:#"Newsfeed-Image-Placeholder"]];
return cell;
Here is the method I'm running when the button is clicked. My thought was that I need the sender here to be a cell, not a button, as the postId property I'm sending in my prepareForSegue only exists on a GFHomeCell:
- (void)commentButtonClick:(id)sender {
[self performSegueWithIdentifier:#"addCommentSegue" sender:sender];
}
Finally my prepareForSegue(I only included the part relevant to this segue):
} else if ([segue.identifier isEqualToString:#"addCommentSegue"]) {
GFPostShowViewController *destViewController = segue.destinationViewController;
GFHomeCell * cell = sender;
destViewController.postId = [cell.postId copy];
destViewController.groupName = [cell.groupName copy];
destViewController.postBody = [cell.postBody copy];
} else {}
I'm new to iOS and this has me stumped so any help would be much appreciated, thanks.
There are basically two common approaches to this situation. One is to search up through the button's superviews until you find the cell. You shouldn't rely on going up one or two levels, because the hierarchy has changed in the past, and may change again (you need to go up two levels in iOS 6, but 3 in iOS 7). You can do it like this,
-(void)commentButtonClick:(UIButton *) sender {
id superView = sender.superview;
while (superView && ![superView isKindOfClass:[UITableViewCell class]]) {
superView = [superView superview];
}
[self performSegueWithIdentifier:#"addCommentSegue" sender:superView];
}
The other way is to assign a tag to your button in cellForRowAtIndexPath: equal to the indexPath.row (if you only have one section), and then use sender.tag to get the indexPath of the cell that contained the tapped button.
Well, one answer would be to just go up a level in the view hierarchy:
- (void)commentButtonClick:(id)sender {
GFHomeCell * cell = (GFHomeCell *) [(UIButton*)sender superview];
if (cell && [cell Class] == [GFHomeCell class]) {
//do whatever with cell.postID
[self performSegueWithIdentifier:#"addCommentSegue" sender:sender];
}
}
Oh, I forget... you may have to go up two levels to get past the contentView property:
GFHomeCell * cell = (GFHomeCell *) [[(UIButton*)sender superview] superview];

Resources