iphone - UIButton tag not being set correctly in cellForRowAtIndexPath -
in uitableviewcell
have uibutton
represents phone when user touches suppose call phone number specified specific object in table cell.
since have multiple buttons , each button have specific phone number trying set tag
property on uibutton
current indexpath.row
, works first 6 cells when cells start being reused tag goes 0 buttons. setting button's tag outside of reuse block thought should proper way in order identify each unique cell.
for testing, set cell.tag
property indexpath.row
, works perfectly, isolated uibutton. ideas on might doing wrong?
- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *schoolcellidentifer = @"schoolcellidentifier"; schoolinfoitem *item = [self.schoolarray objectatindex:indexpath.row]; uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:schoolcellidentifer]; // if cell doesn't existing go ahead , make fresh. if (cell == nil) { // begin phone button view uibutton *phonebutton = [[uibutton alloc] initwithframe:cgrectmake(67, 70, 35, 35)]; phonebutton.tag = 80; uiimageview *phoneview = [[uiimageview alloc] initwithimage:[uiimage imagenamed:@"phone-icon.png"]]; phoneview.frame = cgrectmake(2.5, 2.5, 30, 30); [phonebutton addsubview:phoneview]; [cell.contentview addsubview:phonebutton]; } cell.tag = indexpath.row; phonebutton = (uibutton *) [cell viewwithtag:80]; [phonebutton addtarget:self action:@selector(callphonenumber:) forcontrolevents:uicontroleventtouchupinside]; phonebutton.tag = cell.tag; nslog(@"phonebutton tag: %d", phonebutton.tag); nslog(@"cell tag:%d", cell.tag); return cell }
here method touchevent:
- (void) callphonenumber:(id)sender { uibutton *button = (uibutton *) sender; schoolinfoitem *schoolitem = [self.schoolarray objectatindex:button.tag]; nslog(@"tag at: %d", button.tag); if ([schoolitem.mainphone length] != 0) { nsstring *urlstring = [@"tel://" stringbyappendingstring:schoolitem.mainphone]; nsurl *url = [nsurl urlwithstring:urlstring]; nslog(@"%@", url); [[uiapplication sharedapplication] openurl:url]; } }
tags aren't right way handle this. you'd best subclass uitableviewcell attribute of myperson. [note: replace person school if appropriate] this:
@interface myperson : nsobject @property (...) nsstring *phonenumber; @property (...) nsstring *emailaddress; @end @interface mypersoncell : uitableviewcell @property (readwrite) myperson *person; - (ibaction) callphonenumber; - (ibaction) sendemail; @end
then in tableview:cellforrowatindexpath:
implementation configure cell as
cell.person = [get person datasource section+row];
additionally, uibutton actions link cell (as implied code above) or table view controller itself.
if use xcode storyboards you'll want use 'prototype cells', configure mypersoncell
, add uibutton
, link button action cell.
Comments
Post a Comment