【发布时间】:2023-03-28 08:36:01
【问题描述】:
我对 IOS 很陌生;我通过drawRect方法制作了一些渐变等,现在,如果我想实现它,我将它子类化到视图中。但我在想,有什么方法可以调用方法 drawRect 并让它从 ViewController 的子类中设置视图的背景?
布局是这样的:
背景颜色.h
#import <UIKit/UIKit.h>
@interface BackgroundColor : UIView
@end
背景颜色.m
#import "BackgroundColor"
@implementation BackgroundColor___Fuschia
- (void)drawRect:(CGRect)rect
{
...
}
@end
ViewControllerNav.h
#import <UIKit/UIKit.h>
@interface ViewControllerNav : UIViewController
@end
ViewControllerNav.m
@interface ViewControllerNav ()
@end
@implementation ViewControllerNav
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
我假设我必须导入 BackgroundColor 并初始化方法或?
(PS:我的 drawRect 方法使用 CGRect frame = rect;所以我需要传递的视图大小?)
感谢任何帮助
【问题讨论】:
-
为什么要用drawRect来做背景色?这个“颜色”有什么复杂的地方吗?
-
这不是正确的方法。相反,您应该创建一个 UIView 子类,该子类具有多个颜色属性(或数组,甚至是渐变对象),并据此绘制其背景。不要为每个背景做一个单独的实现。如果需要,您可以在 UIView 子类中定义一些“标准”。然后你可以在视图控制器中做任何你喜欢的事情。
-
非常感谢,我会这样做的
标签: ios objective-c