【问题标题】:IOS - Using drawRect method to set background color on viewIOS - 使用 drawRect 方法在视图上设置背景颜色
【发布时间】: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


【解决方案1】:

要回答您最初的问题,您永远不会直接调用 drawRect:。你打电话给

[self.view setNeedsDisplay];

系统会在适当的时间调用您的 drawRect:。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2011-11-18
    • 2023-03-25
    相关资源
    最近更新 更多