您的位置:首页 > 其它

Presenting View Controllers from Other View Controllers

2014-11-02 14:29 253 查看
转自:https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/ModalViewControllers/ModalViewControllers.html


PresentingViewControllersfromOtherViewControllers

Theabilitytopresentviewcontrollersisatoolthatyouhaveatyourdisposalforinterruptingthecurrentworkflowanddisplayinganewsetofviews.Mostcommonly,anapppresentsaviewcontrollerasatemporaryinterruptiontoobtainimportantinformation
fromtheuser.However,youcanalsousepresentedviewcontrollerstoimplementalternateinterfacesforyourappatspecifictimes.


HowViewControllersPresentOtherViewControllers

Apresentedviewcontrollerisnotaspecificsubclassof
UIViewController
(as
UITabBarController
or
UINavigationController
is).
Instead,anyviewcontrollercanbepresentedbyyourapp.However,liketabbarandnavigationcontrollers,youpresentviewcontrollerswhenyouwanttoconveyaspecificmeaningabouttherelationshipbetweenthepreviousviewhierarchyandthenewlypresented
viewhierarchy.
Whenyoupresentamodalviewcontroller,thesystemcreatesarelationshipbetweentheviewcontrollerthatdidthepresentingandtheviewcontrollerthatwaspresented.Specifically,theviewcontrollerthat
didthepresentingupdatesits
presentedViewController
property
topointtoitspresentedviewcontroller.Similarly,thepresentedviewcontrollerupdatesits
presentingViewController
property
topointbacktotheviewcontrollerthatpresentedit.Figure10-1showstherelationshipbetweentheviewcontrollermanagingthemainscreenintheCalendar
appandthepresentedviewcontrollerusedtocreatenewevents.
Figure10-1PresentedviewsintheCalendar
app.


Anyviewcontrollerobjectcanpresentasingleviewcontrolleratatime.Thisistrueevenforviewcontrollersthatwerethemselvespresentedbyanotherviewcontroller.Inotherwords,youcanchainpresented
viewcontrollerstogether,presentingnewviewcontrollersontopofotherviewcontrollersasneeded.Figure10-2showsavisualrepresentationofthe
chainingprocessandtheactionsthatinitiateit.Inthiscase,whentheusertapstheiconinthecameraview,theapppresentsaviewcontrollerwiththeuser’sphotos.Tappingtheactionbuttoninthephotolibrary’stoolbarpromptstheuserforanappropriate
actionandthenpresentsanotherviewcontroller(thepeoplepicker)inresponsetothataction.Selectingacontact(orcancelingthepeoplepicker)dismissesthatinterfaceandtakestheuserbacktothephotolibrary.TappingtheDonebuttonthendismisses
thephotolibraryandtakestheuserbacktothecamerainterface.
Figure10-2Creatingachainofmodal
viewcontrollers


Eachviewcontrollerinachainofpresentedviewcontrollershaspointerstotheotherobjectssurroundingitinthechain.Inotherwords,apresentedviewcontrollerthatpresentsanotherviewcontrollerhas
validobjectsinbothits
presentingViewController
and
presentedViewController
properties.
Youcanusetheserelationshipstotracethroughthechainofviewcontrollersasneeded.Forexample,iftheusercancelsthecurrentoperation,youcanremoveallobjectsinthechainbydismissingthefirstpresentedviewcontroller.Dismissingaviewcontroller
dismissesnotonlythatviewcontrollerbutalsoanyviewcontrollersitpresented.
InFigure
10-2,apointworthnotingisthatthepresentedviewcontrollersarebothnavigationcontrollers.Youcanpresent
UINavigationController
objects
inthesamewaythatyouwouldpresentacontentviewcontroller.
Whenpresentinganavigationcontroller,youalwayspresentthe
UINavigationController
objectitself,ratherthanpresenting
anyoftheviewcontrollersonitsnavigationstack.However,individualviewcontrollersonthenavigationstackmaypresentotherviewcontrollers,includingothernavigationcontrollers.Figure
10-3showsmoredetailoftheobjectsthatareinvolvedintheprecedingexample.Asyoucansee,thepeoplepickerisnotpresentedbythephotolibrarynavigationcontrollerbutbyoneofthecontentviewcontrollersonitsnavigationstack.
Figure10-3Presentingnavigation
controllersmodally



PresentationStylesforModalViews

ForiPadapps,youcanpresentcontentusingseveraldifferentstyles.IniPhoneapps,presentedviewsalwayscoverthevisibleportionofthewindow,butwhenrunningonaniPad,viewcontrollersusethevalue
intheir
modalPresentationStyle
propertyto
determinetheirappearancewhenpresented.Differentoptionsforthispropertyallowyoutopresenttheviewcontrollersothatitfillsalloronlypartofthescreen.
Figure10-4showsthecorepresentationstylesthatareavailable.(The
UIModalPresentationCurrentContext
style
letsaviewcontrolleradoptthepresentationstyleofitsparent.)Ineachpresentationstyle,thedimmedareasshowtheunderlyingcontentbutdonotallowtapsinthatcontent.Therefore,unlikeapopover,yourpresentedviewsmuststillhavecontrolsthat
allowtheusertodismisstheview.
Figure10-4iPadpresentationstyles


Forguidanceonwhentousethedifferentpresentationstyles,seeModal
ViewiniOSHumanInterfaceGuidelines.


PresentingaViewControllerandChoosingaTransitionStyle

Whenaviewcontrollerispresentedusingastoryboardsegue,itisautomaticallyinstantiatedandpresented.Thepresentingviewcontrollercanconfigurethedestinationviewcontrollerbeforeitispresented.
Formoreinformation,seeConfiguring
theDestinationControllerWhenaSegueisTriggered.
Ifyouneedtopresentaviewcontrollerprogrammatically,youmustdothefollowing:

Createtheviewcontrolleryouwanttopresent.

Setthe
modalTransitionStyle
propertyof
theviewcontrollertothedesiredvalue.

Assignadelegateobjecttotheviewcontroller.Typically,thedelegateisthepresentingviewcontroller.The
delegateisusedbythepresentedviewcontrollerstonotifythepresentingviewcontrollerwhenitisreadytobedismissed.Itmayalsocommunicateotherinformationbacktothedelegate.

Callthe
presentViewController:animated:completion:
method
ofthecurrentviewcontroller,passingintheviewcontrolleryouwanttopresent.

The
presentViewController:animated:completion:
methodpresentstheviewforthespecifiedviewcontrollerobjectandconfigures
thepresenting-presentedrelationshipsbetweenthenewviewcontrollerandthecurrentviewcontroller.Unlessyouarerestoringyourapptosomepreviousstate,youusuallywanttoanimatetheappearanceofthenewviewcontroller.Thetransitionstyleyou
shouldusedependsonhowyouplantousethepresentedviewcontroller.Table10-1liststhetransitionstylesyoucanassigntothe
modalTransitionStyle
property
ofthepresentedviewcontrolleranddescribeshowyoumightuseeachone.

Table10-1Transitionstylesformodalviewcontrollers

Transitionstyle
Usage
UIModalTransitionStyleCoverVertical

Usethisstylewhenyouwanttointerruptthecurrentworkflowtogatherinformationfromtheuser.Youcanalsouseittopresentcontentthattheusermightormightnotmodify.

Forthisstyleoftransition,contentviewcontrollersshouldprovidebuttonstodismisstheviewcontrollerexplicitly.Typically,theseareaDonebuttonandanoptionalCancelbutton.

Ifyoudonotexplicitlysetatransitionstyle,thisstyleisusedbydefault.
UIModalTransitionStyleFlipHorizontal

Usethisstyletochangetheworkmodeofyourapptemporarily.Themostcommonusageforthisstyleistodisplaysettingsthatmightchangefrequently,suchasintheStocksandWeatherapps.Thesesettingscanbemeantfortheentireapportheycanbespecific
tothecurrentscreen.

Forthisstyleoftransition,youusuallyprovidesomesortofbuttontoreturntheusertothenormalrunningmodeofyourapp.
UIModalTransitionStyleCrossDissolve

Usethisstyletopresentanalternateinterfacewhenthedevicechangesorientations.Insuchacase,yourappisresponsibleforpresentinganddismissingthealternateinterfaceinresponsetoorientationchangenotifications.

Media-basedappscanalsousethisstyletofadeinscreensdisplayingmediacontent.

Foranexampleofhowtoimplementanalternateinterfaceinresponsetodeviceorientationchanges,seeCreating
anAlternateLandscapeInterface.
Listing10-1showshowtopresentaviewcontrollerprogrammatically.Whentheuseraddsanewrecipe,the
apppromptstheuserforbasicinformationabouttherecipebypresentinganavigationcontroller.AnavigationcontrollerwaschosensothattherewouldbeastandardplacetoputaCancelandDonebutton.Usinganavigationcontrolleralsomakesiteasier
toexpandthenewrecipeinterfaceinthefuture.Allyouwouldhavetodoispushnewviewcontrollersonthenavigationstack.

Listing10-1Presentingaviewcontrollerprogrammatically

-(void)add:(id)sender{

//Createtherootviewcontrollerforthenavigationcontroller

//ThenewviewcontrollerconfiguresaCancelandDonebuttonforthe

//navigationbar.

RecipeAddViewController*addController=[[RecipeAddViewControlleralloc]

init];


//ConfiguretheRecipeAddViewController.Inthiscase,itreportsany

//changestoacustomdelegateobject.

addController.delegate=self;


//Createthenavigationcontrollerandpresentit.

UINavigationController*navigationController=[[UINavigationControlleralloc]

initWithRootViewController:addController];

[selfpresentViewController:navigationControlleranimated:YEScompletion:nil];

}

WhentheusertapseithertheDoneortheCancelbuttonfromthenewrecipeentryinterface,theappdismissestheviewcontrollerandreturnstheusertothemainview.SeeDismissing
aPresentedViewController.


PresentationContextsProvidetheAreaCoveredbythePresentedViewController

Theareaofthescreenusedtodefinethepresentationareaisdeterminedbythepresentationcontext.Bydefault,thepresentationcontextisprovidedbytherootviewcontroller,whoseframeisusedtodefine
theframeofthepresentationcontext.However,thepresentingviewcontroller,oranyotherancestorintheviewcontrollerhierarchy,canchoosetoprovidethepresentationcontextinstead.Inthatcase,whenanotherviewcontrollerprovidesthepresentation
context,itsframeisusedinsteadtodeterminetheframeofthepresentedview.Thisflexibilityallowsyoutolimitthemodalpresentationtoasmallerportionofthescreen,leavingothercontentvisible.
Whenaviewcontrollerispresented,iOSsearchesforapresentationcontext.Itstartsatthepresentingviewcontrollerbyreadingits
definesPresentationContext
property.
Ifthevalueofthispropertyis
YES
,
thenthepresentingviewcontrollerdefinesthepresentationcontext.Otherwise,itcontinuesupthroughtheviewcontrollerhierarchyuntilaviewcontrollerreturns
YES
or
untilitreachesthewindow’srootviewcontroller.
Whenaviewcontrollerdefinesapresentationcontext,itcanalsochoosetodefinethepresentationstyle.Normally,thepresentedviewcontrollerdetermineshowitpresentedusingits
modalTransitionStyle
property.
Aviewcontrollerthatsets
definesPresentationContext
to
YES
can
alsoset
providesPresentationContextTransitionStyle
to
YES
.
If
providesPresentationContextTransitionStyle
is
setto
YES
,
iOSusesthepresentationcontext’s
modalPresentationStyle
to
determinehowthenewviewcontrollerispresented.


DismissingaPresentedViewController

Whenitcomestimetodismissapresentedviewcontroller,thepreferredapproachistoletthepresentingviewcontrollerdismissit.Inotherwords,wheneverpossible,thesameviewcontrollerthatpresented
theviewcontrollershouldalsotakeresponsibilityfordismissingit.Althoughthereareseveraltechniquesfornotifyingthepresentingviewcontrollerthatitspresentedviewcontrollershouldbedismissed,thepreferredtechniqueisdelegation.
Formoreinformation,seeUsing
DelegationtoCommunicatewithOtherControllers.


PresentingStandardSystemViewControllers

Anumberofstandardsystemviewcontrollersaredesignedtobepresentedbyyourapp.Thebasicrulesforpresentingtheseviewcontrollersarethesameastherulesforpresentingyourcustomcontentviewcontrollers.
However,becauseyourappdoesnothaveaccesstotheviewhierarchymanagedbythesystemviewcontrollers,youcannotsimplyimplementactionsforthecontrolsintheviews.Interactionswiththesystemviewcontrollerstypicallytakeplacethroughadelegate
object.
Eachsystemviewcontrollerdefinesacorrespondingprotocol,whosemethodsyouimplementinyourdelegateobject.Eachdelegateusually
implementsamethodtoeitheracceptwhateveritemwasselectedorcanceltheoperation.Yourdelegateobjectshouldalwaysbereadytohandlebothcases.Oneofthemostimportantthingsthedelegatemustdoisdismissthepresentedviewcontrollerbycalling
the
dismissModalViewControllerAnimated:
method
oftheviewcontrollerthatdidthepresenting(inotherwords,theparentofthepresentedviewcontroller.)
Table10-2listsseveralofthestandardsystemviewcontrollersfoundiniOS.Formoreinformationabout
eachoftheseclasses,includingthefeaturesitprovides,seethecorrespondingclassreferencedocumentation.

Table10-2Standardsystemviewcontrollers

Framework
Viewcontrollers
AddressBookUI
ABNewPersonViewController


ABPeoplePickerNavigationController


ABPersonViewController


ABUnknownPersonViewController

EventKitUI
EKEventEditViewController


EKEventViewController

GameKit
GKAchievementViewController


GKLeaderboardViewController


GKMatchmakerViewController


GKPeerPickerController


GKTurnBasedMatchmakerViewController

MessageUI
MFMailComposeViewController


MFMessageComposeViewController

MediaPlayer
MPMediaPickerController


MPMoviePlayerViewController

UIKit
UIImagePickerController


UIVideoEditorController

Note:Althoughthe
MPMoviePlayerController
class
intheMediaPlayerframeworkmighttechnicallybethoughtofasamodalcontroller,thesemanticsforusingitareslightlydifferent.Insteadofpresentingtheviewcontrolleryourself,youinitializeitandtellittoplayitsmediafile.Theviewcontroller
thenhandlesallaspectsofpresentinganddismissingitsview.(However,the
MPMoviePlayerViewController
class
canbeusedinsteadof
MPMoviePlayerController
asastandardviewcontrollerforplayingmovies.)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐