版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
【移动应用开发技术】[解析苹果官方文档]之[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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2027年福建省泉州市高考物理倒计时模拟卷(含答案解析)
- 2026年品牌宣传上半年推广工作总结
- 工厂外协生产主管2026年二季度外协生产管控总结
- 纺织企业夏季车间降温安全课件
- 2026年秋季初中开学第一课 阳光校园和谐班级
- 2026年秋季统计学专业开学第一课 专业证书与资格认证课件
- 2026年北师大版小学三年级英语上册《Colors》课时教案
- 流行性腮腺炎护理图谱
- 肿瘤科护士护理工作总结
- 妊娠恶阻中医辨证论治
- 军考2026年考试题及答案
- 中国骨科大手术vte预防指南(2025版)
- 2026深静脉血栓形成诊断和治疗指南(第四版)全面解读
- 雨课堂学堂在线学堂云医学数据分析的SPSS软件实现(山东大学)单元测试考核答案
- 2026中医养生精益化管理课件
- 车间内叉车管理制度(3篇)
- (正式版)DB37∕T 4983-2025 《无人机半航空瞬变电磁探测技术规程》
- 居民微信群规范管理制度
- 灌区工程施工管理工作报告(单位、合同工程验收)
- 2025年河南省中等职业教育技能大赛 网络建设与运维赛项(第8套)
- 杭州安全员考试题库及答案解析
评论
0/150
提交评论