您的位置:首页 > 产品设计 > UI/UE

UITableView(Inserting and Deleting Rows and Sections)

2013-05-16 21:58 274 查看


InsertingandDeletingRowsandSections

Atableviewhasaneditingmodeaswellasitsnormal(selection)mode.Whenatableviewgoesintoeditingmode,itdisplaystheeditingandreorderingcontrolsassociatedwithitsrows.Theeditingcontrols,whichareintheleftsideoftherow,allowthe
usertoinsertanddeleterowsinthetableview.Theeditingcontrolshavedistinctiveappearances:



Deletioncontrol


Insertioncontrol
Whenatableviewenterseditingmodeandwhenusersclickaneditingcontrol,thetableviewsendsaseriesofmessagestoitsdatasourceanddelegate,butonlyiftheyimplementthesemethods.
Thesemethodsallowthedatasourceanddelegatetorefinetheappearanceandbehaviorofrowsinthetableview;themessagesalsoenablethemtocarryoutthedeletionorinsertionoperation.

Evenifatableviewisnotineditingmode,youcaninsertordeleteanumberofrowsorsectionsasagroupandhavethoseoperationsanimated.

Thefirstsectionbelowshowsyouhow,whenatableisineditingmode,toinsertnewrowsanddeleteexistingrowsinatableviewinresponsetouseractions.Thesecondsection,“Batch
Insertion,Deletion,andReloadingofRowsandSections,”discusseshowyoucaninsertanddeletemultiplesectionsandrowsanimatedasagroup.

Note:Theprocedureforreorderingrowswhenineditingmodeisdescribedin“Managing
theReorderingofRows.”


InsertingandDeletingRowsinEditingMode


WhenaTableViewisEdited

Atableviewgoesintoeditingmodewhenitreceivesa
setEditing:animated:
message.
Typically(butnotnecessarily)themessageoriginatesasanactionmessagesentwhentheusertapsanEditbuttoninthenavigationbar.Ineditingmode,atableviewdisplaysanyediting(andreordering)controlsthatitsdelegatehas
assignedtoeachrow.Thedelegateassignsthecontrolsasaresultofreturningtheeditingstyleforarowinthe
tableView:editingStyleForRowAtIndexPath:
method.

Note:Ifa
UIViewController
object
ismanagingthetableview,itautomaticallyreceivesa
setEditing:animated:
messagewhentheEditbuttonistapped.Initsimplementationofthismessage,itcanupdatebutton
stateordoanyotherkindoftaskbeforeinvokingthetableview’sversionofthemethod.

Whenthetableviewreceives
setEditing:animated:
,
itsendsthesamemessagetothe
UITableViewCell
object
foreachvisiblerow.Thenitsendsasuccessionofmessagestoitsdatasourceanditsdelegate(iftheyimplementthemethods)asdepictedinthediagraminFigure
7-1.
Figure7-1Callingsequencefor
insertingordeletingrowsinatableview


Afterresending
setEditing:animated:
to
thecellscorrespondingtothevisiblerows,thesequenceofmessagesisasfollows:

Thetableviewinvokesthe
tableView:canEditRowAtIndexPath:
method
ifitsdatasourceimplementsit.Thismethodallowstheapplicationtoexcluderowsinthetableviewfrombeingeditedevenwhentheircell’s
editingStyle
property
indicatesotherwise.Mostapplicationsdonotneedtoimplementthismethod.

Thetableviewinvokesthe
tableView:editingStyleForRowAtIndexPath:
method
ifitsdelegateimplementsit.Thismethodallowstheapplicationtospecifyarow’seditingstyleandthustheeditingcontrolthattherowdisplays.
Atthispoint,thetableviewisfullyineditingmode.Itdisplaystheinsertionordeletioncontrolforeacheligiblerow.

Theusertapsaneditingcontrol(eitherthedeletioncontrolortheinsertioncontrol).Ifheorshetapsadeletioncontrol,aDeletebuttonisdisplayedontherow.Theuserthentapsthat
buttontoconfirmthedeletion.

Thetableviewsendsthe
tableView:commitEditingStyle:forRowAtIndexPath:
message
tothedatasource.Althoughthisprotocolmethodismarkedasoptional,thedatasourcemustimplementitifitwantstoinsertordeletearow.Itmustdotwothings:

Send
deleteRowsAtIndexPaths:withRowAnimation:
or
insertRowsAtIndexPaths:withRowAnimation:
to
thetableviewtodirectittoadjustitspresentation.

Updatethecorrespondingdata-modelarraybyeitherdeletingthereferenceditemfromthearrayoraddinganitemtothearray.

WhentheuserswipesacrossarowtodisplaytheDeletebuttonforthatrow,thereisavariationinthecallingsequencediagrammedinFigure
7-1.Whentheuserswipesarowtodeleteit,thetableviewfirstcheckstoseeifitsdatasourcehasimplementedthe
tableView:commitEditingStyle:forRowAtIndexPath:
method;
ifthatisso,itsends
setEditing:animated:
to
itselfandenterseditingmode.Inthis“swipetodelete”mode,thetableviewdoesnotdisplaytheeditingandreorderingcontrols.Becausethisisauser-drivenevent,italsobracketsthemessagestothedelegateinsideoftwoothermessages:
tableView:willBeginEditingRowAtIndexPath:
and
tableView:didEndEditingRowAtIndexPath:
.
Byimplementingthesemethods,thedelegatecanupdatetheappearanceofthetableviewappropriately.

Note:Thedatasourceshouldnotcall
setEditing:animated:
fromwithinitsimplementationof
tableView:commitEditingStyle:forRowAtIndexPath:
.
Ifforsomereasonitmust,itshouldinvokeitafteradelaybyusingthe
performSelector:withObject:afterDelay:
method.

Althoughyoucanuseaninsertioncontrolasthetriggertoinsertanewrowinatableview,analternativeapproachistohaveanAdd(orplussign)buttoninthenavigationbar.Tappingthebuttonsendsan
actionmessagetotheviewcontroller,whichoverlaysthetableviewwithamodalviewforenteringthenewitem.Oncetheitemisentered,thecontrolleraddsittothedata-modelarrayandreloadsthetable.“An
ExampleofAddingaTable-ViewRow”discussesthisapproach.


AnExampleofDeletingaTable-ViewRow

Thissectiongivesaguidedtourthroughthepartsofaprojectthatworktogethertosetupatableviewforeditingmodeanddeleterowsfromit.Thisprojectusesthenavigationcontrollerandview
controllerarchitecturetomanageitstableviews.Inits
loadView
method,
thecustomviewcontrollercreatesthetableviewandsetsitselftobethedatasourceanddelegate.ItalsosetstherightitemofthenavigationbartobethestandardEditbutton.

self.navigationItem.rightBarButtonItem=self.editButtonItem;

Thisbuttonispreconfiguredtosend
setEditing:animated:
to
theviewcontrollerwhentapped;ittogglesthebuttontitle(betweenEditandDone)andtheBooleaneditingparameteronalternatingtaps.Initsimplementationofthemethod,asshowninListing
7-1,theviewcontrollerinvokesthesuperclassinvocationofthemethod,sendsthesamemessagetothetableview,andupdatestheenabledstateoftheotherbuttoninthenavigationbar(aplus-signbutton,foraddingitems).

Listing7-1Viewcontrollerrespondingto
setEditing:animated:


-(void)setEditing:(BOOL)editinganimated:(BOOL)animated{

[supersetEditing:editinganimated:animated];

[tableViewsetEditing:editinganimated:YES];

if(editing){

addButton.enabled=NO;

}else{

addButton.enabled=YES;

}

}

Whenitstableviewenterseditingmode,theviewcontrollerspecifiesadeletioncontrolforeveryrowexceptthelast,whichhasaninsertioncontrol.Itdoesthisinitsimplementationofthe
tableView:editingStyleForRowAtIndexPath:
method
(Listing7-2).

Listing7-2Customizingtheeditingstyleofrows

-(UITableViewCellEditingStyle)tableView:(UITableView*)tableVieweditingStyleForRowAtIndexPath:(NSIndexPath*)indexPath{

SimpleEditableListAppDelegate*controller=(SimpleEditableListAppDelegate*)[[UIApplicationsharedApplication]delegate];

if(indexPath.row==[controllercountOfList]-1){

returnUITableViewCellEditingStyleInsert;

}else{

returnUITableViewCellEditingStyleDelete;

}

}

Theusertapsthedeletioncontrolinarowandtheviewcontrollerreceivesa
tableView:commitEditingStyle:forRowAtIndexPath:
message
fromthetableview.AsshowninListing7-3,ithandlesthismessagebyremovingtheitemcorrespondingtotherowfromamodelarray
andsending
deleteRowsAtIndexPaths:withRowAnimation:
to
thetableview.

Listing7-3Updatingthedata-modelarrayanddeletingtherow

-(void)tableView:(UITableView*)tableViewcommitEditingStyle:(UITableViewCellEditingStyle)editingStyleforRowAtIndexPath:(NSIndexPath*)indexPath{

//Ifrowisdeleted,removeitfromthelist.

if(editingStyle==UITableViewCellEditingStyleDelete){

SimpleEditableListAppDelegate*controller=(SimpleEditableListAppDelegate*)[[UIApplicationsharedApplication]delegate];

[controllerremoveObjectFromListAtIndex:indexPath.row];

[tableViewdeleteRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationFade];

}

}


AnExampleofAddingaTable-ViewRow

Thissectionshowsprojectcodethatinsertsarowinatableview.Insteadofusingtheinsertioncontrolasthetriggerforinsertingarow,itusesanAddbutton(visuallyaplussign)inthenavigationbar
abovethetableview.Thiscodealsoisbasedonthenavigationcontrollerandviewcontrollerarchitecture.Inits
loadView
method
implementation,theviewcontrollerassignstheAddbuttonastheright-sideitemofthenavigationbarusingthecodeshowninListing7-4.

Listing7-4AddinganAddbuttontothenavigationbar

addButton=[[UIBarButtonItemalloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAddtarget:selfaction:@selector(addItem:)];

self.navigationItem.rightBarButtonItem=addButton;

Notethattheviewcontrollersetsthecontrolstatesforthetitleaswellastheactionselectorandthetargetobject.WhentheusertapstheAdd
button,the
addItem:
messageissenttothetarget(theviewcontroller).ItrespondsasshowninListing
7-5.Itcreatesanavigationcontrollerwithasingleviewcontrollerwhoseviewisputonscreenmodally—itanimatesupwardtooverlaythetableview.The
presentModalViewController:animated:
method
todothis.

Listing7-5RespondingtoatapontheAddbutton

-(void)addItem:sender{

if(itemInputController==nil){

itemInputController=[[ItemInputControlleralloc]init];

}

UINavigationController*navigationController=[[UINavigationControlleralloc]initWithRootViewController:itemInputController];

[[selfnavigationController]presentModalViewController:navigationControlleranimated:YES];

[navigationControllerrelease];

}

Themodal,oroverlay,viewconsistsofasinglecustomtextfield.Theuserenterstextforthenewtable-viewitemandthentapsaSavebutton.Thisbuttonsendsa
save:
action
messagetoitstarget:theviewcontrollerforthemodalview.AsshowninListing7-6,theviewcontrollerextractsthestringvalue
fromthetextfieldandupdatestheapplication’sdata-modelarraywithit.

Listing7-6Addingthenewitemtothedata-modelarray

-(void)save:sender{


UITextField*textField=[(EditableTableViewTextField*)[tableViewcellForRowAtIndexPath:[NSIndexPathindexPathForRow:0inSection:0]]textField];


SimpleEditableListAppDelegate*controller=(SimpleEditableListAppDelegate*)[[UIApplicationsharedApplication]delegate];

NSString*newItem=textField.text;

if(newItem!=nil){

[controllerinsertObject:newIteminListAtIndex:[controllercountOfList]];

}

[selfdismissModalViewControllerAnimated:YES];

}

Afterthemodalviewisdismissedthetableviewisreloaded,anditnowreflectstheaddeditem.


BatchInsertion,Deletion,andReloadingofRowsandSections

The
UITableView
class
allowsyoutoinsert,delete,andreloadagroupofrowsorsectionsatonetime,animatingtheoperationssimultaneouslyinspecifiedways.TheeightmethodsshowninListing
7-7pertaintobatchinsertionanddeletion.Notethatyoucancalltheseinsertionanddeletionmethodsoutsideofananimationblock(asyoudointhedatasourcemethod
tableView:commitEditingStyle:forRowAtIndexPath:
as
discussedin“Inserting
andDeletingRowsinEditingMode”).

Listing7-7Batchinsertionanddeletionmethods

-(void)beginUpdates;

-(void)endUpdates;


-(void)insertSections:(NSIndexSet*)sectionswithRowAnimation:(UITableViewRowAnimation)animation;

-(void)deleteSections:(NSIndexSet*)sectionswithRowAnimation:(UITableViewRowAnimation)animation;

-(void)reloadSections:(NSIndexSet*)sectionswithRowAnimation:(UITableViewRowAnimation)animation;


-(void)insertRowsAtIndexPaths:(NSArray*)indexPathswithRowAnimation:(UITableViewRowAnimation)animation;

-(void)deleteRowsAtIndexPaths:(NSArray*)indexPathswithRowAnimation:(UITableViewRowAnimation)animation;

-(void)reloadRowsAtIndexPaths:(NSArray*)indexPathswithRowAnimation:(UITableViewRowAnimation)animation;

Note:The
reloadSections:withRowAnimation:
and
reloadRowsAtIndexPaths:withRowAnimation:
methods,
whichwereintroducediniOS3.0,allowyoutorequestthetableviewtoreloadthedataforspecificsectionsandrowsinsteadofloadingtheentirevisibletableviewbycalling
reloadData
.

Toanimateabatchinsertion,deletion,andreloadingofrowsandsections,callthecorrespondingmethodswithinananimationblockdefinedbysuccessivecallsto
beginUpdates
and
endUpdates
.
Ifyoudon’tcalltheinsertion,deletion,andreloadingmethodswithinthisblock,rowandsectionindexesmaybeinvalid.Callsto
beginUpdates
and
endUpdates
can
benested;allindexesaretreatedasiftherewereonlytheouterupdateblock.
Attheconclusionofablock—thatis,after
endUpdates
returns—thetableviewqueriesitsdata
sourceanddelegateasusualforrowandsectiondata.Thusthecollectionobjectsbackingthetableviewshouldbeupdatedtoreflecttheneworremovedrowsorsections.


AnExampleofBatchedInsertionandDeletionOperations

Toinsertanddeleteagroupofrowsandsectionsinatableview,firstpreparethearray(orarrays)thatarethesourceofdataforthesectionsandrows.Afterrowsandsectionsaredeletedandinserted,
theresultingrowsandsectionsarepopulatedfromthisdatastore.
Next,callthe
beginUpdates
method,
followedbyinvocationsof
insertRowsAtIndexPaths:withRowAnimation:
,
deleteRowsAtIndexPaths:withRowAnimation:
,
insertSections:withRowAnimation:
,
or
deleteSections:withRowAnimation:
.
Concludetheanimationblockbycalling
endUpdates
.Listing
7-8illustratesthisprocedure.

Listing7-8Insertinganddeletingablockofrowsinatableview

-(IBAction)insertAndDeleteRows:(id)sender{

//originalrows:Arizona,California,Delaware,NewJersey,Washington


[statesremoveObjectAtIndex:4];//Washington

[statesremoveObjectAtIndex:2];//Delaware

[statesinsertObject:@"Alaska"atIndex:0];

[statesinsertObject:@"Georgia"atIndex:3];

[statesinsertObject:@"Virginia"atIndex:5];


NSArray*deleteIndexPaths=[NSArrayarrayWithObjects:

[NSIndexPathindexPathForRow:2inSection:0],

[NSIndexPathindexPathForRow:4inSection:0],

nil];

NSArray*insertIndexPaths=[NSArrayarrayWithObjects:

[NSIndexPathindexPathForRow:0inSection:0],

[NSIndexPathindexPathForRow:3inSection:0],

[NSIndexPathindexPathForRow:5inSection:0],

nil];

UITableView*tv=(UITableView*)self.view;


[tvbeginUpdates];

[tvinsertRowsAtIndexPaths:insertIndexPathswithRowAnimation:UITableViewRowAnimationRight];

[tvdeleteRowsAtIndexPaths:deleteIndexPathswithRowAnimation:UITableViewRowAnimationFade];

[tvendUpdates];


//endingrows:Alaska,Arizona,California,Georgia,NewJersey,Virginia

}

Thisexampleremovestwostringsfromanarray(andtheircorrespondingrows)andinsertsthreestringsintothearray(alongwiththeircorrespondingrows).Thenextsection,“Ordering
ofOperationsandIndexPaths,”explainsparticularaspectsoftherow(orsection)insertionanddeletionbehavior.


OrderingofOperationsandIndexPaths

YoumighthavenoticedsomethinginthecodeshowninListing7-8thatseemspeculiar.
Thecodecallsthe
deleteRowsAtIndexPaths:withRowAnimation:
method
afteritcalls
insertRowsAtIndexPaths:withRowAnimation:
.
However,thisisnottheorderinwhich
UITableView
completes
theoperations.Itdefersanyinsertionsofrowsorsectionsuntilafterithashandledthedeletionsofrowsorsections.Thetableviewbehavesthesamewaywithreloadingmethodscalledinsideanupdateblock—thereloadtakesplacewithrespecttotheindexes
ofrowsandsectionsbeforetheanimationblockisexecuted.Thisbehaviorhappensregardlessoftheorderingoftheinsertion,deletion,andreloadingmethodcalls.
Deletionandreloadingoperationswithinananimationblockspecifywhichrowsandsectionsintheoriginaltableshouldberemovedorreloaded;insertionsspecifywhichrowsandsectionsshouldbeaddedtothe
resultingtable.Theindexpathsusedtoidentifysectionsandrowsfollowthismodel.Insertingorremovinganiteminamutablearray,ontheotherhand,mayaffectthearrayindexusedforthesuccessiveinsertionorremovaloperation;forexample,ifyou
insertanitematacertainindex,theindexesofallsubsequentitemsinthearrayareincremented.
Anexampleisusefulhere.Sayyouhaveatableviewwiththreesections,eachwiththreerows.Thenyouimplementthefollowinganimationblock:

Beginupdates.

Deleterowatindex1ofsectionatindex0.

Deletesectionatindex1.

Insertrowatindex1ofsectionatindex1.

Endupdates.

Figure7-2illustrateswhattakesplaceaftertheanimationblockconcludes.
Figure7-2Deletionofsectionandrowand
insertionofrow
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: