繁体   English   中英

如何在UIImageView中添加UILabel

[英]how to add a UILabel in UIImageView

我的应用程序中有大图片。 我动态创建它,我想在此图像上添加UILabel:

UIImageView *thumbnailImage;
thumbnailImage = [[UIImageView alloc] initWithFrame:CGRectMake(xImage, yImage, imageWidth, imageHeight)];
UILabel *lblTitle = [[UILabel alloc] init];
lblTitle.text = @"SomeText"; 
lblTitle.frame = CGRectMake(xTitle, yTitle , titleWidth ,titleHeight);
[thumbnailImage setContentMode:UIViewContentModeScaleAspectFill];
thumbnailImage.clipsToBounds = YES;
[thumbnailImage addSubview:lblTitle];

但是[thumbnailImage addSubview:UILabel]; 代码不起作用。

任何人有任何想法吗?

我想在图片底部添加一些文本,例如新闻文章。

因此,我用下面的代码解决了这个问题,如果有人有更好的主意,请分享。

UIImageView *thumbnailImage;
thumbnailImage = [[UIImageView alloc] initWithFrame:CGRectMake(xImage, yImage, imageWidth, imageHeight)];
UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(xImage,imageHeight - titleHeight , titleWidth , titleHeight )];
UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(xTitle, yTitle , titleWidth ,titleHeight)];
titleView.alpha = 0.3;
[thumbnailImage setContentMode:UIViewContentModeScaleAspectFill];
thumbnailImage.clipsToBounds = YES;
[self.view addSubview:thumbnailImage];
[self.view addSubview:titleView];
lblTitle.textLabel.text = @"SomeText";

首先我使用下面的代码行:

 [titleView addSubview:lblTitle]

但是titleView的alpha titleView影响lblTitle并使它透明。 因此,删除此行后, lblTitle文本将显得清晰明亮。

thumbnailImage是一个UIView,因此您可以向其添加子视图。

[thumbnailImage addSubview:UILabel];

使用以下::对其进行编辑:

[thumbnailImage addSubview:lblTitle];

这将起作用。 :)

最好使用框架来初始化标签。

您应该在标签上添加文字

您应该将UILabel对象( lblTitle )添加到imageview而不是UILabel类型。

经过这些更正,您的代码应如下所示:

UIImageView *thumbnailImage;
thumbnailImage = [[UIImageView alloc] initWithFrame:CGRectMake(xImage, yImage, imageWidth, imageHeight)];
[thumbnailImage setContentMode:UIViewContentModeScaleAspectFill];
thumbnailImage.clipsToBounds = YES;
UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(xTitle, yTitle , titleWidth ,titleHeight)];
lblTitle.textLabel.text = @"Your text";
[thumbnailImage addSubview:lblTitle];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM