[英]Custom UIPicker - Placing an image, text and subtext in one row?
通過查看Mr.T鏈接到的名為“ CountryPickerDemo”的項目(看看它!),我意識到使圖片和文本顯示在一行中的核心方法是:
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)行用於組件:(NSInteger)組件重用View:(UIView *)視圖
這是我在代碼中使其工作的方式:
//Custom view and rows are created inside this method. There doesn't seem to be an easier way.
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
//IF view doesn't exist, then create it.
if (!view)
{
//View creation.
view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 140, 30)]; //(0, 0, 280, 30)]; //x & y width & height
//Rows label creation.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 110, 24)]; //(35, 3, 245, 24)];
label.textColor = [UIColor blackColor];
label.tag = 1;
[view addSubview:label];
//Rows image creation.
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 24, 24)]; //(3, 3, 24, 24)];
imgView.contentMode = UIViewContentModeScaleAspectFit;
imgView.tag = 2;
[view addSubview:imgView];
}
//INPUT data into rows. P.S. I have TWO components; not just one like in the picture above. If you only need one component like in the picture above, then ignore the IF ELSE statements and just use the code inside the IF statement only.
if (component == 0)
{
//Load actual text into 1st label sections.
((UILabel*)[view viewWithTag:1]).text = [NSString stringWithFormat:@"%@", _componentOne[row]];
//Load actual images into 1st image sections.
((UIImageView*)[view viewWithTag:2]).image = [UIImage imageNamed:@"imageName.png"];
}
else
{
//Load actual text into 2nd label sections.
((UILabel*)[view viewWithTag:1]).text = [NSString stringWithFormat:@"%@", _componentTwo[row]];
//Load actual images into 2nd image sections.
((UIImageView*)[view viewWithTag:2]).image = [UIImage imageNamed:@"imageName.png"];
}
//EXAMPLE CODE.
//((UILabel*)[view viewWithTag:1]).text = [[self class] countryNames][(NSUInteger)row];
//NSString *imagePath = [NSString stringWithFormat:@"CountryPicker.bundle/%@", [[self class] countryCodes][(NSUInteger) row]];
//((UIImageView*)[view viewWithTag:2]).image = [UIImage imageNamed:imagePath];
return view;
}
注意:在占位符@“ imageName.png”中鍵入您自己的圖像名稱,以查看其外觀。 您可能需要解決,通過使用數組來放置不同的圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.