首页 > 代码库 > IOS 读取xib里的子控件

IOS 读取xib里的子控件

interface ViewController ()
/**获取.plist数据*/
@property (nonatomic,strong) NSArray *aps;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    
    //九宫格的总列数
    int totalColumns=5;
    
    //1.1个格子的尺寸
    CGFloat appW=50;
    CGFloat appH=60;
    
    //2.计算间隙 =(控制器view的宽度 -5*应用宽度)/应用宽度+1
    CGFloat marginX=(self.view.frame.size.width-totalColumns*appW)/(totalColumns+1);
    CGFloat marginY=55;
    //3.要的应用个数创建对应的格子
    
    for (int index=0; index<self.aps.count; index++)
    {
        NSBundle *bundle=[NSBundle mainBundle];
        //读取xib文件(会创建AppsView.xib中的描述的所有对象。并且按顺序放到数组中返回) 
NSArray *objs=[bundle loadNibNamed:@"AppsView"
owner:nil options:nil];
UIView
*appView=[objs lastObject];

//添加view
[self.view addSubview:appView];

//设置frame
int row=index/ totalColumns; int col=index% totalColumns;

//计算x和y CGFloat appx=marginX+col*(appW+marginX);
CGFloat appY
=marginY+row *(appH + marginY);
appView.frame
=CGRectMake(appx, appY, appW, appH);
//设置数据
Apps *app=self.aps[index];

//设置图片(xib中的appView取子控件 UIImageView)

// UIImageView *iconView=appView.subviews[0]; //方式1

UIImageView *iconView=(UIImageView *)[appView viewWithTag:10];//方式2
iconView.image=[UIImage imageNamed:app.icon];

//设置名称(xib中的appView取子控件 UILabel)

// UILabel *nameLabel=appView.subviews[1];//方式1

UILabel *nameLabel=(UILabel *)[appView viewWithTag:20];//方式2
nameLabel.text=
app.name;
}

}

 

IOS 读取xib里的子控件