在iOs的Objective-C中绘制矩形



我是Objective C的初学者,我想在iPhone屏幕上画一个矩形。

我所做的是:

-创建一个名为CustomView 的新类

-按如下方式调整AppDelegate.m文件:

#import "AppDelegate.h"
#import "CustomView.h"
@interface AppDelegate ()
@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
CGRect bigRect =  CGRectMake (100, 100, 100, 100) ;
CGRect smallRect =  CGRectMake (50, 50, 50, 50);
CustomView * bigView = [[ CustomView alloc ]  initWithFrame:bigRect ];
CustomView * smallView = [[ CustomView alloc ]  initWithFrame:smallRect ];
[ bigView setBackgroundColor :[ UIColor redColor ]];
[ smallView setBackgroundColor :[ UIColor blueColor ]];
[ self.window addSubview:bigView ];
[ self.window addSubview:smallView ];
return YES;

}

当我模拟这个时,我只得到一个白色屏幕。我怀疑我可能需要更新类CustomView本身?

为什么要使用appDelegate?您需要添加方法来在ViewController实现中创建用户界面。

请尝试更简单的解决方案:

-(void)drawBox
    UIView *myBox  = [[UIView alloc] initWithFrame:CGRectMake(180, 35, 10, 10)];
    myBox.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:myBox];
}

然后在viewDidLoad中调用该方法。CGRectMake的参数是x、y、高度和宽度,您可能需要根据需要进行编辑。

我还建议查看这篇文章-https://www.google.ru/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CBsQFjAAahUKEwj0-vXRz4PJAhWCjiwKHd36Bo0&url=https%3A%2F%2Developer.apple.com%2Flibrary%2Fios%2Fdocumentation%2FUIKit%2FReference%2FUIView_Class%2F&usg=AFQjCNHj3LrxW69BtP-2db5kevpbQ_AuKw&sig2=LTnzngT5im-5Jr8wWNeqbQ&cad=rjt

最新更新