本文我们将从实例想大家介绍iOS应用开发如何新建UIView的子类。包括自定义绘图函数、将新视图绑定到主窗口等内容。

大致步骤

1) 新建一个UIView的子类(@interface HypnosisView : UIView)

2) 自定义绘图函数:(void) drawRect:(CGRect)rect

◆确定绘图范围:CGRect bounds=[self bounds]

◆获得CGContext, CGContextRef context=UIGraphicsGetCurrentContext();

◆进行绘图操作

3) 将新视图绑定到主窗口

◆在HypnosisterAppDelegate中添加一个成员变量HypnosisView *view;

◆确定绘图范围

◆在didFinishLaunchingWithOptions中增加子视图:[_window addSubview:view];

◆进行显示 [_window makeKeyAndVisible];

待确定事项:

1) CGContextStrokePath的功能

2) makeKeyAndVisible消息的功能

关键代码如下:

Java代码

1) 绑定处理:

  1. -(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  2. {
  3. NSLog(@"didFinishLaunchingWithOptions.");
  4. CGRectdrawingArea=[_windowbounds];
  5. view=[[HypnosisViewalloc]initWithFrame:drawingArea];
  6. [viewsetBackgroundColor:[UIColoryellowColor]];
  7. [_windowaddSubview:view];
  8. //Overridepointforcustomizationafterapplicationlaunch.
  9. [_windowmakeKeyAndVisible];
  10. returnYES;
  11. }

2) 绘图处理:

  1. -(void)drawRect:(CGRect)rect
  2. {
  3. NSLog(@"EnteringthedrawingfunctionofHyponsisView.");
  4. //Getthedrawingrectangle
  5. CGRectbounds=[selfbounds];
  6. //Calculatethereferences
  7. CGPointcenter;
  8. center.x=bounds.origin.x+bounds.size.width/2.0;
  9. center.y=bounds.origin.y+bounds.size.height/2.0;
  10. floatradius=hypot(bounds.size.width,bounds.size.height)/2.0;
  11. //PrepareDrawing
  12. CGContextRefcontext=UIGraphicsGetCurrentContext();
  13. CGContextSetLineWidth(context,10);
  14. [[UIColorgreenColor]setStroke];
  15. //Drawingthecircles
  16. for(floatr=radius;r>0;rr=r-25)
  17. {
  18. CGContextAddArc(context,center.x,center.y,r,0.0,M_PI*2.0,YES);
  19. CGContextStrokePath(context);
  20. }
  21. }

运行效果:

iOS应用开发教程:新建UIView的子类(ios ui开发)  UIView iOS 第1张
转载请说明出处
知优网 » iOS应用开发教程:新建UIView的子类(ios ui开发)

发表评论

您需要后才能发表评论