gpt4 book ai didi

iphone - UIView 的 drawRect 没有被调用

转载 作者:行者123 更新时间:2023-11-29 13:47:27 25 4
gpt4 key购买 nike

我正在尝试在网格中显示水平和/或垂直线。所以我创建了一个 UIView 子类 GridLines,它在 drawRect: 中绘制线条。然后我创建其中两个(一个垂直,一个不是),并将它们作为 subview 添加到我的主视图 (Canvas) 中,也是 UIView 派生的。我添加到 Canvas 的其他自定义 subview 已正确显示、删除等,但 GridLines 对象不是,它们的 drawRect:永远不会被叫到。当我在 [Canvas drawRect:](现已禁用)中使用此画线代码时,它会正确显示网格。

查看类似的问题,似乎大多数有此问题的人都在非 UIView 派生类中调用 drawRect,但我的是 UIView.

我是不是漏掉了什么?

网格线.h:

#import <UIKit/UIKit.h>
@interface GridLines : UIView
{
BOOL mVertical;
}
- (id) initWithFrame: (CGRect) _frame vertical: (BOOL) _vertical;
@end

网格线.m:

#import "GridLines.h"
@implementation GridLines
- (id) initWithFrame: (CGRect) _frame vertical: (BOOL) _vertical
{
if ((self = [super initWithFrame: _frame]))
{
mVertical = _vertical;
}

return self;
}

- (void) drawRect: (CGRect) _rect
{
NSLog(@"[GridLines drawRect]");
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor clearColor] set];
UIRectFill([self bounds]);

if (mVertical)
{
for (int i = 50; i < self.frame.size.width; i += 50)
{
CGContextBeginPath(context);
CGContextMoveToPoint(context, (CGFloat)i, 0.0);
CGContextAddLineToPoint(context, (CGFloat)i, self.frame.size.height);
[[UIColor grayColor] setStroke];
CGContextSetLineWidth(context, 1.0);
CGContextDrawPath(context, kCGPathFillStroke);
}
}
else
{
for (int j = 50; j < self.frame.size.height; j += 50)
{
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0.0, (CGFloat)j);
CGContextAddLineToPoint(context, self.frame.size.width, (CGFloat)j);
[[UIColor grayColor] setStroke];
CGContextSetLineWidth(context, 1.0);
CGContextDrawPath(context, kCGPathFillStroke);
}
}
}
@end

在另一个 UIView 派生类中:

- (void) createGrids
{
mHorizontalLines = [[GridLines alloc] initWithFrame: self.frame vertical: NO];
mVerticalLines = [[GridLines alloc] initWithFrame: self.frame vertical: YES];
[self addSubview: mHorizontalLines];
[self addSubview: mVerticalLines];
}

最佳答案

您可能遇到了frame v bounds 问题。

mHorizontalLines = [[GridLines alloc] initWithFrame: self.frame vertical: NO];
mVerticalLines = [[GridLines alloc] initWithFrame: self.frame vertical: YES];

frame 保存在 superview 的坐标空间中,如果 self.frame 的偏移大于它的宽度,当您将这些新 View 设置到该框架时,它们'将被裁剪到 self 的 rect。

尝试将其更改为 self.bounds,它应该有 origin = {0,0}

关于iphone - UIView 的 drawRect 没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6742070/

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