这是一个荒谬可笑的问题,但我遇到了麻烦。我创建了一个包含三个 UIView 的 .xib。一个绿色 View ,一个红色 View 和一个蓝色 View 。当我在模拟器中运行时,会显示绿色 View 。我在我的 Green View 上放了 2 个按钮。一个显示红色 View ,一个显示蓝色 View 。这是我的绿色 View 代码:
#import "IDGreenView.h"
#import "IDRedView.h"
#import "IDBlueView.h"
#import "IDGreenView.h"
@interface IDGreenView()
@property (weak, nonatomic) IBOutlet UIButton *RedViewButton;
@property (weak, nonatomic) IBOutlet UIButton *BlueViewButton;
@end
@implementation IDGreenView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (IBAction)showRedView:(id)sender {
[self.window addSubview:[[IDRedView alloc]init]];
}
- (IBAction)showBlueView:(id)sender {
[self.window addSubview:[[IDBlueView alloc]init]];
}
@end
这是我的红色 View 代码:
#import "IDRedView.h"
@implementation IDRedView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
@end
我可以看到它进入了 Red View 的 initWithFrame 方法,所以我知道调用是正确的。我需要做什么才能显示红色 View ?
谢谢。
-------------------------------------------- --- 更新评论 ------------------------------------ --------------
没有。我将以下代码放在 ViewController 中,但也没有用。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self.view addSubview:[[IDRedView alloc] initWithFrame:self.view.bounds]];
}
为什么不显示?
最佳答案
我发现您的代码存在两个主要问题:
首先,为什么要将 View 添加到窗口中? [self.window addSubview...]
。
如果 IDGreenView
是 UIView
的子类,您应该只说:[self addSubview...]
其次,您正在创建没有框架的 IDRedView
和 IDBlueView
(再次假设它们都是 UIView
的子类)。尝试使用框架创建它们,如下所示:
// You may have to adjust the frame to fit your needs
[[IDRedView alloc] initWithFrame:CGRectMake(0,0,20,20)];
希望这对您有所帮助!
关于ios - Objective-C 用不同的 UIView 替换当前的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19575024/