2016-11-23 86 views
0

對於每個UIImageView,我想添加標籤子視圖到它。 這是我的類繼承的形式的UIImageViewObjective-C:添加子視圖只適用於一個視圖

-(instancetype)initWithFrame:(CGRect)frame 
{ 
if (self=[super initWithFrame:frame]) { 
    self.categoryLabel=[[UILabel alloc]initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, 50)]; 

    self.categoryLabel.textAlignment=NSTextAlignmentCenter; 
    self.categoryLabel.font=[UIFont systemFontOfSize:20]; 
    self.categoryLabel.textColor=[UIColor whiteColor]; 

    [self addSubview:self.categoryLabel]; 
    NSLog(@"%@",self.subviews); 
} 
return self; 
} 
-(void)setModel:(HorizontalModel *)model 
{ 
_model=model; 
self.categoryLabel.text=self.model.category; 
[self sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"XXXXX%@",self.model.imgURL]] placeholderImage:[UIImage imageNamed:@"obama"]]; 
    } 

這是我的視圖中的控制器的代碼。

-(void)addImage:(NSNotification *)notification 
{ 
self.HArrayLists=notification.userInfo[@"array"]; 
for (int i=0; i<[self.HArrayLists count]; i++) { 
    JTImageView *imageView=[[JTImageView alloc] initWithFrame:CGRectMake(i*310, 0, 300, 200)]; 
    imageView.model=[HorizontalModel restaurantsDetailWithDict: self.HArrayLists[i]]; 
    [self.mediaScrollView addSubview:imageView]; 
} 
self.mediaScrollView.contentSize=CGSizeMake(310*[self.HArrayLists count], 0); 

} 

事實證明,只有第一個imageView顯示一個標籤,而其餘的imageViews只顯示圖像。

+1

您確定HArrayLists中的所有數據都包含所有條目的文本嗎?只要調試,你可以這樣做:imageView.categoryLabel.text = @「Test」;並註釋掉imageView.model =部分。很可能你的數據是@「」,所以沒有什麼可以顯示 – GeneCode

+0

贊同Rocotilos;也考慮使用self.HArrayLists的-enumerateObjectsUsingBlock方法;它看起來更清潔 \t [self.HArrayLists enumerateObjectsUsingBlock:^(HArrayListsInst * OBJ,NSUInteger IDX,BOOL *停止){ \t}]; –

+0

爲什麼你看到self.mediaScrollView高到0? –

回答

1

我覺得你的問題的核心是線路:

self.categoryLabel=[[UILabel alloc]initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, 50)]; 

您抵消x和x和圖像的y值標籤的y位置。這會將它們放置在圖像區域之外並與圖像剪輯一起使其不可見。我認爲該行應該是

self.categoryLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, 50)]; 

將所有標籤放置在每個圖像的左上角。

說了這麼多,我還想提供一些建議。

首先使所有變量名以小寫字母開頭。所以self.HArrayLists應該是self.hArrayLists

其次嘗試使變量名稱與其內容匹配。所以再看看self.HArrayLists,或許就像self.imageData

接下來我會以不同的方式完成構圖。我將有一個UIView我添加了UILabelUIImageView實例。使用這樣的父視圖來佈置兩個子視圖通常會使生活更輕鬆。

我也會考慮使用UICollectionViewUICollectionViewController而不是UIScrollView。您需要做一些工作才能讓您瞭解集合視圖的工作方式。但是,您將獲得更好的性能和更好的佈局管理。

最後,研究約束條件。它們是構建現代應用程序的重要組成部分,可以輕鬆適應不同大小的屏幕,旋轉和佈局。

+0

另外,你可以使用界限而不是框架,因爲這裏面的視圖,而不是外面是它聽起來像你想要的。我喜歡這裏使用UICollectionView的建議。它將完成你想要的東西,正如drekka所說,你在性能和佈局管理方面獲得了很多。使用dequeueCellWithReuseIdentifer()的好處非常驚人!:) [UICollectionView](https://developer.apple.com/reference/uikit/uicollectionview?language=objc) –

0

您需要正確設置爲categoryLabelframe

self.categoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, frame.origin.y, frame.size.width, 50)]; 
相關問題