gpt4 book ai didi

ios - 以编程方式将 subview 添加到 Storyboard 中的预定义 subview 不起作用

转载 作者:行者123 更新时间:2023-11-28 22:38:43 25 4
gpt4 key购买 nike

我在 Storyboard中有一个 ViewController,该 Storyboard由两个 UIView 和底部的一个表组成。屏幕的中心包含一个在 Storyboard中定义的 UIView,带有一个名为 middleSectionView 的导出。我想以编程方式将 subview 添加到 middleSectionView。以编程方式添加的 subview 没有出现。这是我的代码:

RoundedRect.m:
#import "RoundedRect.h"

@implementation RoundedRect

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSLog(@"RoundedRect: initWithFrame: entering");
UIView* roundedView = [[UIView alloc] initWithFrame: frame];
roundedView.layer.cornerRadius = 5.0;
roundedView.layer.masksToBounds = YES;
roundedView.layer.backgroundColor = [UIColor redColor].CGColor;

UIView* shadowView = [[UIView alloc] initWithFrame: frame];
shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
shadowView.layer.shadowRadius = 5.0;
shadowView.layer.shadowOffset = CGSizeMake(3.0, 3.0);
shadowView.layer.opacity = 1.0;
// [shadowView addSubview: roundedView];
}
return self;
}
@end


.h:
...
@property (strong, nonatomic) IBOutlet UIView *middleSectionView;

.m:
...
#import "RoundedRect.h"
...
- (void)viewDidLoad
{
RoundedRect *roundRect= [[RoundedRect alloc] init];
roundRect.layer.masksToBounds = YES;
roundRect.layer.opaque = NO;
[self.middleSectionView addSubview:roundRect]; // This is not working
[self.middleSectionView bringSubviewToFront:roundRect];
// [self.view addSubview:roundRect]; // This didn't work either
// [self.view bringSubviewToFront:roundRect]; // so is commented out
...
}

最佳答案

您看不到 RoundedRect 的原因是您调用了错误的初始化程序:这一行

RoundedRect *roundRect= [[RoundedRect alloc] init];

不会调用 initWithFrame: 初始化程序来完成初始化您的 RoundedRect View 的所有工作。您需要将调用更改为

RoundedRect *roundRect= [[RoundedRect alloc] initWithFrame:CGRectMake(...)];

并将所需的框架坐标放在上面的 ... 处。

关于ios - 以编程方式将 subview 添加到 Storyboard 中的预定义 subview 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15189787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com