iphone - 如何以编程方式创建自定义 View 类?

标签 iphone ios ios6 custom-view

<分区>

我想创建一个非常简单的自定义 View ,上面有一些 UIlabel,我应该怎么做。任何教程或建议将不胜感激。我是新手,之前没有尝试过。

我用 xib 试过了。

@interface MyCustomView : UIView

@property (strong, nonatomic) IBOutlet UILabel *Label;

@end

实现

#import "MyCustomTimer.h"
@implementation MyCustomView
-(id)initWithCoder:(NSCoder *)aDecoder{
      if ((self = [super initWithCoder:aDecoder])){
      [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self     options:nil] objectAtIndex:0]];
       }
     return self;
}
@end

但我需要以编程方式进行,请帮忙。谢谢

最佳答案

这里有一个简单的方法,希望对你有帮助。

//in subclassed UIView 
#import "CustomView.h"
@implementation CustomView

 - (id)initWithFrame:(CGRect)frame
 { 
  self = [super initWithFrame:frame];
  if (self) {
    // Initialization code
    // initilize all your UIView components
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(20,30, 200, 44)];
    label1.text = @"i am label 1";
    [self addSubview:label1]; //add label1 to your custom view

    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(20,80, 200, 44)];
    label2.text = @"i am label 2";
    [self addSubview:label2]; //add label2 to your custom view



    [label1 release];//i am using without ARC, comment if u are using ARC
    [label2 release];//i am using without ARC, comment if u are using ARC
  }
   return self;
  }



   // in your class where u want to use that view
  #import "ViewController.h"
  #import "CustomView.h"//import it

  @interface ViewController ()

  @end

  @implementation ViewController

 - (void)viewDidLoad
  {
     [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    //create your view where u want
    CustomView *cv = [[CustomView alloc]initWithFrame:CGRectMake(10, 10, 230, 400)];   //create an instance of your custom view
     [self.view addSubview:cv]; // add to your main view
    [cv release];//comment if u are using ARC
 }


关于iphone - 如何以编程方式创建自定义 View 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17994473/

相关文章:

iOS 区域监控

iphone - 使用 ARC 处理 NSError - 泄漏

ios - IBOutlet Label 获取不到数据

iphone - ios中的信用卡支付

iphone - 格式化 float 以显示在具有两位数的字符串中?

iphone - iPhone开发人员:UIWebView Youtube崩溃。我可以试一下吗?

ios - NSString大小不考虑希腊呼吸痕

uitableview - indexPathForCell 在 IOS 7 下返回 NULL,在 IOS 6 下工作正常

iphone - 如何在 iOS5 上运行 iOS 4.3.3 开发的应用程序?

iphone - 强制 UIImagePickerController 以横向模式拍摄视频