gpt4 book ai didi

ios - initWithImage 工作正常 initWithFrame 被调用不止一次

转载 作者:行者123 更新时间:2023-11-28 21:56:37 24 4
gpt4 key购买 nike

我正在对 UIImageViewUIView 进行子类化,以生成带有数字的简单彩色图 block 。如果我正在使用 UIImageView,我会使用 initWithImage 方法。如果我使用 UIView,则使用方法 initWithFrame。红色方 block 图像或以编程方式生成的红色 View 用于初始化。
可以在两个屏幕截图中看到问题:使用 initWithImage 时 - 一切正常。如果正在使用 initWithFrame 方法,我将以多个白色 View 结束,而没有任何信息按正常 View 的顺序创建。附上所有截图和代码。

这是使用 initWithImage 初始化时的样子: initWithImage

- (id)initWithImage:(UIImage *)image {
self = [super initWithImage:image];
if (self) {
//Some non-important, label-related stuff.
[self addSubview:self.numberLabel];
}
return self;
}

这就是 initWithFrame 的样子:
initWithFrame

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.redView = [self redViewWithFrame:frame];
[self addSubview:self.redView];
//label-related stuff
}
return self;
}


- (UIView *)redViewWithFrame:(CGRect)frame {
UIView *view = [[UIView alloc] initWithFrame:frame];
view.backgroundColor = [UIColor redColor];
view.alpha = 1;
return view;
}

还有 for 循环,从另一个类(UIScrollView 子类)调用这些初始化器。标签值是在 View 初始化后设置的。

- (void)setNumberOfBlocks:(NSInteger)numberOfBlocks {
_blocks = [[NSMutableArray alloc] init];

CGSize contentSize;
contentSize.width = BLOCK_WIDTH * (numberOfBlocks);
contentSize.height = BLOCK_HEIGHT;

self.contentSize = contentSize;

for (int i = 0; i < numberOfBlocks; i++) {
CGFloat totalWidth = BLOCK_WIDTH * i;
CGRect frame = CGRectMake(0, 0, BLOCK_WIDTH, BLOCK_HEIGHT);

frame.origin.x = totalWidth;


BlockView *view = [[BlockView alloc] initWithImage:[UIImage imageNamed:@"block.png"]];
OR!!!
BlockView *view = [[BlockView alloc] initWithFrame:frame];


view.frame = frame;
NSString *number = [NSString stringWithFormat:@"%ld", (long)i + 1];
view.numberLabel.text = number;


[self addSubview:view];
[_blocks addObject:view];
}
}

谷歌搜索给我的印象是这是一个非常普遍的问题,但我还没有找到任何解决方案来解决这个问题。而且,我仍然不明白,为什么数字顺序完全正确,唯一的问题是 View 位置。

最佳答案

问题是您将红色 View 的框架设置为父 View 的框架而不是其边界。由于红色 View 是 BlockView 的 subview ,它的框架需要相对于它的父 View ,你可以通过边界获得它(不清楚为什么你甚至需要红色 View ,而不是将 block View 的背景颜色设置为红色)。

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.redView = [self redViewWithFrame:self.bounds];
[self addSubview:self.redView];
//label-related stuff
}
return self;
}

关于ios - initWithImage 工作正常 initWithFrame 被调用不止一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26320943/

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