版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
【移動應用開發技術】[解析蘋果官方文檔]之[UIViewClassReference]
The
UIView
classdefinesarectangularareaonthescreenandtheinterfacesformanagingthecontentinthatarea.Atruntime,aviewobjecthandlestherenderingofanycontentinitsareaandalsohandlesanyinteractionswiththatcontent.The
UIView
classitselfprovidesbasicbehaviorforfillingitsrectangularareawithabackgroundcolor.Moresophisticatedcontentcanbepresentedbysubclassing
UIView
andimplementingthenecessarydrawingandevent-handlingcodeyourself.TheUIKitframeworkalsoincludesasetofstandardsubclassesthatrangefromsimplebuttonstocomplextablesandcanbeusedas-is.Forexample,a
UILabel
objectdrawsatextstringanda
UIImageView
objectdrawsanp_w_picpath.
UIView類定義了手機屏幕上的一塊方形區域,并提供了管理此區域內模塊內容的接口。程序運行時,view負責處理本視圖區域內所有模塊的渲染(render:(v.)
process
(anoutlinep_w_picpath)
using
colourandshading
inorder
tomakeitappear
solid
andthree-dimensional->
對輪廓圖進行色彩及背景陰影處理,以產生三維立體實物效果),以及用戶與這些模塊之間的交互。UIView類本身就提供了為此方形區域填充背景色的基礎方法。若想展現較為復雜的視圖,我們可以創建子類,繼承UIView,并按照自己的需求來實現(drawing)繪圖以及(event-handling)事件處理的方法。UIKit框架也包含了一系列標準的UIView子類:從簡單的UIButton到復雜的UITableView,這些類都可以拿來直接用。比如:UILabel對象->繪制一個字符串;UIImageView對象->繪制一張圖片。Becauseviewobjectsarethemainwayyourapplicationinteractswiththeuser,theyhaveanumberofresponsibilities.Herearejustafew:
view對象是我們的應用與用戶交互的主要途徑,因此它有如下幾項職責:DrawingandanimationViewsdrawcontentintheirrectangularareausingtechnologiessuchasUIKit,CoreGraphics,andOpenGLES.Someview
properties
canbeanimatedtonewvalues.
1).繪圖+動畫view通過UIKit,CoreGraphics,OpenGLES等技術繪制方形區域的內容;view的某些屬性值的改變可以賦與動畫效果。LayoutandsubviewmanagementAviewmaycontainzeroormoresubviews.Eachviewdefinesitsowndefaultresizingbehaviorinrelationtoitsparentview.Aviewcandefinethesizeandpositionofitssubviewsasneeded.2).布局+子視圖管理view可包含0或多個子視圖;每個view都定義了在父視圖大小發生變化時,重新調整自身大小的默認方法;view可以定義子視圖的位置和大小。EventhandlingAviewisaresponderandcanhandletoucheventsandothereventsdefinedbythe
UIResponder
class.
Viewscanusethe
addGestureRecognizer:
methodtoinstallgesturerecognizerstohandlecommongestures.
3).事件處理UIView繼承自UIResponder和NSObject;view本身就是一個responder,因此它能處理觸摸點擊事件或其他UIResponder類定義的事件;view可以通過addGestureRecognizer方法給視圖加載手勢識別器,處理常見的手勢。Viewscanembedotherviewsandcreatesophisticatedvisualhierarchies.Thiscreatesaparent-childrelationshipbetweentheviewbeingembedded(knownasthe
subview)andtheparentviewdoingtheembedding(knownasthe
superview).Normally,asubview’svisibleareaisnotclippedtotheboundsofitssuperview,butiniOSyoucanusethe
clipsToBounds
propertytoalterthatbehavior.Aparentviewmaycontainanynumberofsubviewsbuteachsubviewhasonlyonesuperview,whichisresponsibleforpositioningitssubviewsappropriately.view可以重重嵌套,產生復雜的視圖層級結構(在父視圖superview之上嵌入子視圖subview)。通常子視圖的可視范圍不會局限于父視圖的邊界,但我們可以修改clipToBounds屬性值為yes將子視圖超出父視圖的部分裁剪掉不顯示。父視圖可以包含多個子視圖,但每個子視圖只能擁有一個父視圖。父視圖負責將子視圖擺放在合適的位置。Thegeometryofaviewisdefinedbyits
frame,
bounds,and
center
properties.The
frame
definestheoriginanddimensionsoftheviewinthecoordinatesystemofitssuperviewandiscommonlyusedduringlayouttoadjustthesizeorpositionoftheview.The
center
propertycanbeusedtoadjustthepositionoftheviewwithoutchangingitssize.The
bounds
definestheinternaldimensionsoftheviewasitseesthemandisusedalmostexclusivelyincustomdrawingcode.Thesizeportionofthe
frame
and
bounds
rectanglesarecoupledtogethersothatchangingthesizeofeitherrectangleupdatesthesizeofboth.
view的幾何屬性由frame,bounds,center共同決定:frame:
view在其superview的坐標系中的起始位置frame.origin和尺寸frame.size;常用在布局中調整視圖的方位和大小center:不改變view的大小,只調整view的位置bounds:view在自身坐標系中的尺寸;幾乎只用于自定義繪圖。frame.size和bounds.size是緊密相聯的,任意一方改變,另一方均隨之改變。Fordetailedinformationabouthowtousethe
UIView
class,see
ViewProgrammingGuideforiOS.
NOTEIniOS2.x,themaximumsizeofa
UIView
objectis1024x1024points.IniOS3.0andlater,viewsarenolongerrestrictedtothismaximumsizebutarestilllimitedbytheamountofmemorytheyconsume.Itisinyourbestintereststokeepviewsizesassmallaspossible.RegardlessofwhichversionofiOSisrunning,youshouldconsidertilinganycontentthatissignificantlylargerthanthedimensionsthescreen.
在iOS2.x系統中,視圖對象的最大尺寸為1024*1024.但在iOS3.0及其之后的版本中,視圖大小不再局限于這個數字,但仍舊受到所占用內存大小的限制。開發者最好將視圖的大小設置得越小越好。不論運行的iOS是哪一版本,都應把比手機屏幕大很多的視圖劃分(tile)為小模塊。CreatingaView
創建視圖Tocreateaviewprogrammatically,youcanusecodelikethefollowing:CGRect
viewRect=CGRectMake(10,10,100,100);UIView*myView=[[UIViewalloc]initWithFrame:viewRect];Thiscodecreatestheviewandpositionsitatthepoint(10,10)initssuperview’scoordinatesystem(onceitisaddedtothatsuperview).Toaddasubviewtoanotherview,youusethe
addSubview:
method.IniOS,siblingviewsmayoverlapeachotherwithoutanyissues,allowingcomplexviewplacement.The
addSubview:
methodplacesthespecifiedviewontopofothersiblings.Youcanspecifytherelativez-orderofasubviewbyaddingitusingthe
insertSubview:aboveSubview:
and
insertSubview:belowSubview:
methods.Youcanalsoexchangethepositionofalreadyaddedsubviewsusingthe
exchangeSubviewAtIndex:withSubviewAtIndex:
method.
以代碼方式創建視圖:調用initWithFrame:方法;上述代碼創建了一個視圖,并將其在父視圖坐標系統中的起始位置設置為了(10,10)點。我們通過調用addSubview:方法添加子視圖。在iOS系統中,siblingviews(擁有相同的父視圖)可以互相重疊,而且可以進行復雜的位置替換:addSubview:方法將某一特定視圖覆蓋于其他同級別的子視圖(siblings)之上;insertSubview:aboveSubview:和insertSubview:belowSubview:方法指定視圖在z坐標軸方向上的顯示順序;exchangeSubviewAtIndex:withSubviewAtIndex:方法調換兩個同級別子視圖之間的z坐標軸順序。Whencreatingaview,itisimportanttoassignanappropriatevaluetothe
autoresizingMask
propertytoensuretheviewresizescorrectly.Viewresizingprimarilyoccurswhentheorientationofyourapplication’sinterfacechangesbutitmayhappenatothertimesaswell.Forexample,callingthe
setNeedsLayout
methodforcesyourviewtoupdateitslayout.
此段有關視圖的autoresizingMask屬性解析見此文:/4655765/1738641TheViewDrawingCycle視圖的繪制周期Viewdrawingoccursonanas-neededbasis.Whenaviewisfirstshown,orwhenallorpartofitbecomesvisibleduetolayoutchanges,thesystemaskstheviewtodrawitscontents.ForviewsthatcontaincustomcontentusingUIKitorCoreGraphics,thesystemcallstheview’s
drawRect:
method.Yourimplementationofthismethodisresponsiblefordrawingtheview’scontentintothecurrentgraphicscontext,whichissetupbythesystemautomaticallypriortocallingthismethod.Thiscreatesa
staticvisualrepresentationofyourview’scontentthatcanthenbedisplayedonthescreen.
視圖繪制僅在需要的時候才會進行。當某個視圖首次顯示,或其全部/部分內容由于布局變化從不可見狀態變為可見狀態時,系統將要求視圖進行內容繪制。如果視圖包含的是自定義的UIKit或CoreGraphics內容,系統會調用視圖的drawRect:方法。我們在實現這個方法時,需要將視圖的內容繪制到當前的繪圖環境中去(這個繪圖環境已經在調用drawRect:方法之前由系統自動搭建好了),從而生成視圖內容的靜態可視界面,隨后顯示到屏幕上。Whentheactualcontentofyourviewchanges,itisyourresponsibilitytonotifythesystemthatyourviewneedstoberedrawn.Youdothisbycallingyourview’s
setNeedsDisplay
or
setNeedsDisplayInRect:
methodoftheview.Thesemethodsletthesystemknowthatitshouldupdatetheviewduringthenextdrawingcycle.Becauseitwaitsuntilthenextdrawingcycletoupdatetheview,youcancallthesemethodsonmultipleviewstoupdatethematthesametime.
此段有關視圖的繪制周期解析見官方文檔ViewProgrammingGuideforiOS章節。
略析見此文:/4655765/1738677NOTEIfyouareusingOpenGL
EStodoyourdrawing,youshouldusethe
GLKView
classinsteadofsubclassing
UIView.FormoreinformationabouthowtodrawusingOpenGL
ES,see
OpenGLESProgrammingGuideforiOS.
如果你使用的是OpenGLES框架繪圖,你應該使用的是GLKView類,而不是繼承自UIView類。詳見官方文檔OpenGLESProgrammingGuideforiOS章節。Animations動畫Changestoseveralviewpropertiescanbeanimated—thatis,changingthepropertycreatesananimationthatconveysthechangetotheuseroverashortperiodoftime.The
UIView
classdoesmostoftheworkofperformingtheactualanimationsbutyoumuststillindicatewhichpropertychangesyouwanttobeanimated.Therearetwodifferentwaystoinitiateanimations:
IniOS4andlater,usetheblock-basedanimationmethods.(Recommended)Usethebegin/commitanimationmethods.
view的某些屬性值的改變可以做出動畫效果-將整個屬性的變化過程在較短的時間內展示給用戶。雖然UIView類負責大部分的動畫操控,但開發者仍需要指定出哪些屬性的改變是需要添加動畫的。有兩種開啟動畫的方式:1.在iOS4及之后的系統中,使用基于代碼塊block的動畫方法(推薦)2.使用動畫的begin、commit方法;Theblock-basedanimationmethods(suchas
animateWithDuration:animations:)greatlysimplifythecreationofanimations.Withonemethodcall,youspecifytheanimationstobeperformedandtheoptionsfortheanimation.However,block-basedanimationsareavailableonlyiniOS4andlater.IfyourapplicationrunsonearlierversionsofiOS,youmustusethe
beginAnimations:context:
and
commitAnimations
classmethodstomarkthebeginningandendingofyouranimations.
Thefollowingpropertiesofthe
UIView
classareanimatable:
基于代碼塊block的動畫方法(例如animateWithDuration:animations:)極大簡化了創建動畫的步驟,只需在此方法中指定動畫內容及動畫選項這兩個參數。但此方法僅適用于iOS4及以上的系統,對于老版本的系統則需要使用beginAnimations:context:和commitAnimations方法,它們分別標志著動畫的開始和結束。UIView的以下屬性都是可以加動畫效果的:@property
frame@property
bounds@property
center@property
transform@property
alpha@property
backgroundColor@property
contentStretchFormoreinformationabouthowtoconfigureanimations,see
ViewProgrammingGuideforiOS.
有關視圖的動畫配置,詳見官方文檔ViewProgrammingGuideforiOS章節。ThreadingConsiderations涉及多線程的考慮Manipulationstoyourapplication’suserinterfacemustoccuronthemainthread.Thus,youshouldalwayscallthemethodsofthe
UIView
classfromcoderunninginthemainthreadofyourapplication.Theonlytimethismaynotbestrictlynecessaryiswhencreatingtheviewobjectitselfbutallothermanipulationsshouldoccuronthemainthread.
應用中所有的UI操作都必須在主線程中進行。除了創建視圖的方法之外,其他所有UIView類中的方法都必須在主線程中被調用。SubclassingNotes關于子類的繼承
The
UIView
classisakeysubclassingpointforvisualcontentthatalsorequiresuserinteractions.Althoughtherearemanygoodreasonstosubclass
UIView,itisrecommendedthatyoudosoonlywhenthebasic
UIView
classorthestandardsystemviewsdonotprovidethecapabilitiesthatyouneed.Subclassingrequiresmoreworkonyourparttoimplementtheviewandtotuneitsperformance.Forinformationaboutwaystoavoidsubclassing,see
AlternativestoSubclassing.
UIView的子類常用于實現視圖展示和用戶交互的雙重效果。建議:如果UIView或系統已實現好的UIView子類可以滿足你的需求,那就不要再自定義子類了。關于如何規避對子類的創建,參閱
AlternativestoSubclassing章節。MethodstoOverride可以重寫的方法Whensubclassing
UIView,thereareonlyahandfulofmethodsyoushouldoverrideandmanymethodsthatyoumightoverridedependingonyourneeds.Because
UIView
isahighlyconfigurableclass,therearealsomanywaystoimplementsophisticatedviewbehaviorswithoutoverridingcustommethods,whicharediscussedintheAlternativestoSubclassingsection.Inthemeantime,thefollowinglistincludesthemethodsyoumightconsideroverridinginyour
UIView
subclasses:
創建UIView子類時,僅有為數不多的幾個方法應該重寫,剩下的很多方法則是根據自己的需要可重寫可不重寫。UIView具有很高的可配置度,也有很多種其他的途徑可以代替實現復雜的視圖結構,而不用重寫方法。
以下這幾個方法我們可以考慮是否需要重寫:Initialization:初始化initWithFrame:
-Itisrecommendedthatyouimplementthismethod.Youcanalsoimplementcustominitializationmethodsinadditionto,orinsteadof,thismethod.initWithCoder:
-ImplementthismethodifyouloadyourviewfromanInterfaceBuildernibfileandyourviewrequirescustominitialization.layerClass
-ImplementthismethodonlyifyouwantyourviewtouseadifferentCoreAnimationlayerforitsbackingstore.Forexample,ifyourviewusestilingtodisplayalargescrollablearea,youmightwanttooverridethismethodandreturnthe
CATiledLayer
class.Drawingandprinting:繪圖&打印drawRect:
-Implementthismethodifyourviewdrawscustomcontent.Ifyourviewdoesnotdoanycustomdrawing,avoidoverridingthismethod.
drawRect:forViewPrintFormatter:
-Implementthismethodonlyifyouwanttodrawyourview’scontentdifferentlyduringprinting.
Constraints:約束requiresConstraintBasedLayout
-Implementthisclassmethodifyourviewclassrequiresconstraintstoworkproperly.updateConstraints
-Implementthismethodifyourviewneedstocreatecustomconstraintsbetweenyoursubviews.alignmentRectForFrame:,
frameForAlignmentRect:
-Implementthesemethodstooverridehowyourviewsarealignedtootherviews.Layout:布局sizeThatFits:
-Implementthismethodifyouwantyourviewtohaveadifferentdefaultsizethanitnormallywouldduringresizingoperations.Forexample,youmightusethismethodtopreventyourviewfromshrinkingtothepointwheresubviewscannotbedisplayedcorrectly.
layoutSubviews
-Implementthismethodifyouneedmoreprecisecontroloverthelayoutofyoursubviewsthaneithertheconstraintorautoresizingbehaviorsprovide.
didAddSubview:,
willRemoveSubview:
-Implementthesemethodsasneededtotracktheadditionsandremovalsofsubviews.willMoveToSuperview:,
didMoveToSuperview
-Implementthesemethodsasneededtotrackthemovementofthecurrentviewinyourviewhierarchy.willMoveToWindow:,
didMoveToWindow
-Implementthesemethodsasneededtotrackthemovementofyourviewtoadifferentwindow.EventHandling:事件處理touchesBegan:withEvent:,
touchesMoved:withEvent:,
touchesEnded:withEvent:,
touchesCancelled:withEvent:
-Implementthesemethodsifyouneedtohandletoucheventsdirectly.(Forgesture-basedinput,usegesturerecognizers.)gestureRecognizerShouldBegin:
-Implementthismethodifyourviewhandlestoucheventsdirectlyandmightwanttopreventattachedgesturerecognizersfromtriggeringadditionalactions.AlternativestoSubclassing不用創建子類,還可以怎么做?Manyviewbehaviorscanbeconfiguredwithouttheneedforsubclassing.Beforeyoustartoverridingmethods,considerwhethermodifyingthefollowingpropertiesorbehaviorswouldprovidethebehavioryouneed.許多視圖行為的實現都不用通過創建子類的方式,在重寫部分方法之前,思考一下是否通過設置以下的屬性就可以達到你想要的效果:addConstraint:
-Defineautomaticlayoutbehaviorfortheviewanditssubviews.addConstraint->
決定視圖和子視圖的自動布局行為autoresizingMask
-Providesautomaticlayoutbehaviorwhenthesuperview’sframechanges.Thesebehaviorscanbecombinedwithconstraints.autoresizingMask->當父視圖的frame改變時,決定本視圖的自動布局行為;可與上一個方法結合使用contentMode
-Provideslayoutbehaviorfortheview’scontent,asopposedtothe
frame
oftheview.Thispropertyalsoaffectshowthecontentisscaledtofittheviewandwhetheritiscachedorredrawn.
contentMode->
決定視圖的bounds變化時,視圖內容如何布局(對比frame屬性);此屬性影響到視圖的內容應該如何伸縮以適應本視圖,以及視圖是需要緩存還是重繪制。contentStretch
-Definesportionsoftheviewasbeingstretchable.Thisbehavioristypicallyusedtoimplementbuttonsandotherresizableviewswithsophisticatedlayoutneedswhereredrawingthevieweverytimewouldaffectperformance.contentStretch->決定視圖的各部分是否可以伸縮。此行為通常用于實現按鈕和其他大小可變的視圖;這些視圖的布局需求較為復雜,可能每次重新繪制視圖時都會影響到性能表現。hidden
or
alpha
-Changethetransparencyoftheviewasawholeratherthanhidingorapplyingalphatoyourview’srenderedcontent.
hidden/alpha修改視圖整體透明度,不用再隱藏/改變視圖所渲染的某一部分內容的透明度backgroundColor
-Settheview’scolorratherthandrawingthatcoloryourself.backgroundColor直接設置視圖顏色,省得再自行繪制Subviews-Ratherthandrawyourcontentusinga
drawRect:
method,embedp_w_picpathandlabelsubviewswiththecontentyouwanttopresent.
subviews->不用通過drawRect:方法繪制內容,可以考慮直接在p_w_picpath或label上疊放你想展示的子視圖;Gesturerecognizers-Ratherthansubclasstointerceptandhandletoucheventsyourself,youcanusegesturerecognizerstosendan
actionmessage
toatargetobject.
gesturerecognizers->與其創建子類截獲觸屏事件,不如用gesturerecognizers發送action消息給target對象。Animations-Usethebuilt-i
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 河南平頂山市郟縣兩校聯考2026年初中二模化學試題(含答案)
- 2026 年護理專業學生謹防高薪護工虛假招聘詐騙課
- 2026 年護理帶教激勵考核機制構建與運用
- 2026 年護理質量持續改進項目實施分享
- 2026 年泌尿外科腹腔鏡手術圍術期護理
- 2026六年級下冊英語期末考試卷及答案
- 2026年保密教育線上培訓考試考試真題及答案
- 2026年地質行業地質災害評估方案
- 2026年高職(園林技術)園林植物栽培實驗綜合測試題及答案
- 2026年企業信息化建設全面實施規劃
- 2025年茂名港集團有限公司招聘筆試真題
- 2026安徽師范大學專職輔導員招聘3人(第二批)筆試參考題庫及答案詳解
- 2026年車險查勘定損人員上崗考核試卷及答案
- 成都教科附屬2026初一入學語文分班考試真題含答案
- 2026書記員面試題目及答案
- 2026-2027北師大版七(上)數學第一章 豐富的圖形世界 單元測試卷
- 2026中煤華利新疆炭素科技有限公司招聘16人筆試歷年典型考點題庫附帶答案詳解
- 中國骨科大手術vte預防指南(2025版)
- 肺癌病人營養支持護理
- 2026年江蘇省安全員C1證(機械類)考試真題(含答案解析)
- 2026中醫養生精益化管理課件
評論
0/150
提交評論