[英]use a custom uiview inside a storyboard
因此,我正在使用storyboard
并且已将UIView
拖入我的UIViewController
内。
我们将其称为customView,它的类称为SPView
。 该类在检查器窗口中设置。 在SPView.h
内部,有许多属性
我尝试了以下方法:
如果将标签拖到UIView
内部(在storyboard
),则会显示该标签,但是无法通过拖放将其连接到SPView.h
中的其中一个插座。
如果创建带有标签的新XIB文件,则可以根据需要进行连接。
然后在我的UIViewController
我尝试了以下两种方法之一:
self.customView =[[SPView alloc] initWithFrame:CGRectMake(60, 60, 200, 260)]
self.customView =[[SPView alloc]init];
并在我的SPView中,如果使用此命令:
- (id)initWithCoder:(NSCoder *)aDecoder {
NSLog(@"initWitchCoder called");
if ((self = [super initWithCoder:aDecoder])) {
//[self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"SPView" owner:self options:nil] objectAtIndex:0]];
[self baseInit];
}
标签未显示。
如果我取消注释,则永远调用initWithCoder
,应用最终崩溃。
我想要的是:
可以在情节提要中或以编程方式设置UIViewController
内的自定义UIView
(但最好将图形数据设置在storyboard
提要中或在单独的.XIB文件中设置,以便更轻松地检查它们)。
你能帮我吗?
您可以在UIViewController类中定义以下方法,并为SPView创建一个XIB。
- (SPView*) loadCustomViewFromNib
{
SPView *spView = nil;
NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"SPView"
owner:nil
options:nil];
for (id object in array)
{
if ([object isKindOfClass:[SPView class]])
{
spView = (SPView*)object;
break;
}
}
return spView;
}
并已如下所示初始化了SPView
self.customView = [self loadCustomViewFromNib];
您不能将商店拖到自定义类uiview类。 仅在使用xib时允许使用。 您只能在该自定义视图的父ViewController中放置该出口。 您可以在自定义视图的子视图中设置标签。 并可以使用以下代码轻松访问它们。 假设您在自定义视图中有一个带有标签:2的子视图
- (id)initWithCoder:(NSCoder *)aDecoder {
NSLog(@"initWitchCoder called");
if ((self = [super initWithCoder:aDecoder])) {
//[self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"SPView" owner:self options:nil] objectAtIndex:0]];
UILabel *lbl = (UILabel *)[self viewWithTag:2];
[self baseInit];
}
因此您必须将标签设置为子视图才能访问它们
在uiviewcontroller中,您必须直接退出插座。 不需要这样,它将自动初始化
@property (weak, nonatomic) IBOutlet SPView *customView; //right and easy way
X self.customView =[[SPView alloc] initWithFrame:CGRectMake(60, 60, 200, 260)]
X self.customView =[[SPView alloc]init];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.