gpt4 book ai didi

ios - 自动调整 UIImageView 大小以适应底层图像

转载 作者:行者123 更新时间:2023-11-29 10:34:51 26 4
gpt4 key购买 nike

我在 xib 文件中定义了一个自定义 View ,其中有一个 UIImageView。

图像以编程方式添加。我不知道编译时的确切图像大小。

imageView 的高度在设计上是恒定的,宽度必须是动态的。

UIImageView 应该在设置后自动调整大小以适合图像,但它不会。

我试过:

  • 在 UI Designer 中设置“Intristic size = Placeholder”。
  • 设置不同的模式,例如“Aspect fit”或“Aspect fill”
  • 设置约束(见截图)
  • 在代码中设置大小(见代码)
  • 在 Google 和 Stackoverflow 上搜索并尝试代码示例

什么都没有帮助实现预期的结果。

There's my xib screenshot

这是我的代码:

@implementation EVACustomNavBar

-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if(self)
{
[[NSBundle mainBundle] loadNibNamed:@"EVACustomNavBar" owner:self options:nil];
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.frame.size.width, self.frame.size.height);
[self addSubview:self.view];
}
return self;
}

-(void)setLogo:(UIImage *)logo
{
NSLog(NSStringFromCGRect(self.logoView.bounds));
NSLog(NSStringFromCGSize(logo.size));
self.logoView.backgroundColor = [UIColor blackColor];
self.logoView.image = logo;
CGRect ivFrame = self.logoView.bounds;
CGFloat aspectRatio = logo.size.width / logo.size.height;
ivFrame.size.width = ivFrame.size.height * aspectRatio;
self.logoView.bounds = ivFrame;
NSLog(NSStringFromCGRect(self.logoView.bounds));
}

@end

我尝试在我的 ViewController 文件中的 viewDidLoad 和 viewDidAppear 调用 setLogo。

我尝试了 logoView.bounds 和 logoView.frame。输出是:

logoView.bounds before setting: {{0, 0}, {0, 44}}
logo size: {82, 71}
logoView.bounds after setting{{0, 0}, {50.816898, 44}}

但是我看到了这个:There's my simulator screenshot

所以即使设置 UIImageView 的框架也无济于事。

最佳答案

尝试在 IB 中创建宽度约束,而不是设置 ImageView 的边界或框架,将其附加到类中的 IBOutlet 并更新宽度约束。

关于ios - 自动调整 UIImageView 大小以适应底层图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27639330/

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