如何在UIImageView中添加UILabel

时间:2013-11-24 12:30:07

标签: ios objective-c uiimageview uilabel

我的应用中有大图像。我动态创建它,我想在此图像上添加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];代码不起作用。

任何人都有任何想法?

3 个答案:

答案 0 :(得分:2)

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

所以我用下面的代码解决它,如果有任何人有更好的想法请分享。

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值影响lblTitle并使其透明。删除此行后lblTitle文字显得清晰明亮。

答案 1 :(得分:0)

thumbnailImage是一个UIView,所以你可以为它添加子视图。而不是写行

[thumbnailImage addSubview:UILabel];

使用以下::

编辑它
[thumbnailImage addSubview:lblTitle];

这会奏效。 :)

答案 2 :(得分:0)

最好用它的框架初始化标签。

您应该在标签上添加文字

您应该将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];