在代码中构建界面时,创建具有一定偏移量的 UIImageView 是非常常见的任务。 我可以看到两种初始化原点不等于 (0,0) 的 UIImageView 的方法:
第一种方法只需要图像文件名和来源,但包含很多代码(我们可以使用 frame.origin = CGPointMake(x,y);
减少一行):
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image_filename"]];
CGRect frame = imgView.frame;
frame.origin.x = 150;
frame.origin.y = 100;
undoBg.frame = frame;
第二种方法代码少得多,看起来更干净,但我们需要对图像大小进行硬编码:
UIImageView *shadowView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 150, 800, 600)];
shadowView.image = [UIImage imageNamed:@"image_filename"];
什么是您的最佳实践,为什么? 谢谢。
最佳答案
硬编码图像大小是 Unnamed numerical constants 的一种形式这是 Code Smell 的指示
应该尽可能避免这种事情,因为它会生成更难维护且容易出现人为错误的代码。例如,当您的图形艺术家更改图像大小时会发生什么?您现在必须更改很多东西(图像,以及代码中对图像大小进行硬编码的每个地方),而不是只更改一件事(图像)
请记住,您编写代码不是为了今天,而是为了后来的人维护您的代码。
如果有的话,如果你真的关心额外的代码行,那么你会抽象加载 UIImageView 到一个类别中,这样它就可以在任何地方使用(注意这段代码没有经过测试):
@interface UIImageView (MyExtension)
-(UIImageView*)myLoadImage:(NSString*)named at:(CGPoint)location;
@end
@implementation
-(UIImageView*)myLoadImage:(NSString*)named at:(CGPoint)location
{
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:named]];
CGRect frame = imgView.frame;
frame.origin.x = location.x;
frame.origin.y = location.y;
return imgView;
}
@end
然后你可以简单地做:
UIImageView* imageView = [UIImageView myLoadImage:@"image_filename" at:CGPointMake(150,100)];
关于iphone - 使用非零原点初始化 UIImageView 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9501003/