簡體   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