简体   繁体   English

在调用drawRect之前初始化自定义UIView

[英]Initialize custom UIView before drawRect gets called

I need to customize a UIView by calling its drawRect method, so I subclass UIView and name it MyView. 我需要通过调用它的drawRect方法来自定义UIView,所以我将UIView子类化并将其命名为MyView。 The drawing will depend on some variable(myString in this example), so I need to initialize the variable before drawRect starts. 绘图将取决于某个变量(本例中为myString),因此我需要在drawRect启动之前初始化变量。 My MyView.h looks like 我的MyView.h看起来像

@interface MyView : UIView
@property (strong, nonatomic) NSString *myString;
@end

In the viewController.m, if I do the following 在viewController.m中,如果我执行以下操作

MyView *myView = [MyView alloc] initWithFrame:someRect];
[myView setMyString:@"string value"];

[self.view addSubview:myView];

everything works as expected, the myString is set before drawRect get called. 一切都按预期工作,myString在drawRect被调用之前设置。

The problem I am trying to solve is if I want to add the MyView to the view controller by using Interface Builder(drag and drop an UIView to the view controller's view and change its class to MyView), where is the point that I can set myString before drawRect gets called? 我想解决的问题是,如果我想通过使用Interface Builder将MyView添加到视图控制器(将UIView拖放到视图控制器的视图并将其类更改为MyView),我可以在哪里设置点调用drawRect之前的myString?

set it in your view controller 在视图控制器中设置它

-(void) viewDidLoad {
    MyView *myView = self.view;
   [myView setMyString:@"string value"];
 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM