IOS中使用.xib檔案封裝一個自訂View

來源:互聯網
上載者:User

標籤:

1.建立一個繼承UIView的自訂view,假設類名叫做 MyAppVew

#import <UIKit/UIKit.h>@class MyApp;@interface MyAppView : UIView@property(strong,nonatomic) MyApp*app;+(instancetype)appView;@end

MyAppView.h

#import "MyAppView.h"#import "MyApp.h"@interface MyAppView ()@property (weak, nonatomic) IBOutlet UIImageView *iconView;@property (weak,nonatomic) IBOutlet UILabel *nameLable;@end@implementation MyAppView-(void)setApp:(MyApp *) app{    _app=app;    self.iconView.image=[UIImage imageNamed:app.icon];    self.nameLable.text=app.name;    //NSLog(@"%@", app.icon);}+(instancetype) appView{        NSBundle *bundle=[NSBundle mainBundle];    NSArray *objs=[bundle loadNibNamed:@"AppInfoView" owner:nil options:nil];    return [objs lastObject];}+(instancetype) appViewWithApp:(MyApp *)app{    MyAppView *appView=[self appView];    appView.app=app;    return appView;}@end

 

2.建立一個MyAppVIew.xib檔案來描述MyAppView內部結構

3.修改UIView的類型為MyAppView類型

4.將內部的子控制項跟MyAppView進行屬性連線

5.MyAppView提供一個模型屬性

@interface MyAppView ()

 

@property (weak, nonatomic) IBOutlet UIImageView *iconView;

@property (weak,nonatomic) IBOutlet UILabel *nameLable;

 

 

6.重寫模型屬性的set方法,因為set方法中可以拿到外界傳遞的模型資料

 

-(void)setApp:(MyApp *) app{    _app=app;    self.iconView.image=[UIImage imageNamed:app.icon];    self.nameLable.text=app.name;    //NSLog(@"%@", app.icon);}

 

7.把模型資料拆開,分別設定資料到對應的子控制項中

 

8.補充:提供一個建立MyAppView的類方法,將讀取的.xib檔案的代碼屏蔽起來

 

+(instancetype) appView{        NSBundle *bundle=[NSBundle mainBundle];    NSArray *objs=[bundle loadNibNamed:@"AppInfoView" owner:nil options:nil];    return [objs lastObject];}+(instancetype) appViewWithApp:(MyApp *)app{    MyAppView *appView=[self appView];    appView.app=app;    return appView;}

通過封裝資料,對mvc有了初步認識。

IOS中使用.xib檔案封裝一個自訂View

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.