天天看點

用xib建立一個UIView(xib自定義view,修改不了frame的問題)

1.建立一個CustomerView的檔案,commend+n,如圖:

用xib建立一個UIView(xib自定義view,修改不了frame的問題)

2.用xib建立一個view,命名為CustomerView,commend+n,如圖:

用xib建立一個UIView(xib自定義view,修改不了frame的問題)

3.修改xib中如下資料,

3.1 首先修改Custom Class中的Class為:CustomerView,即建立與CustomerView的關聯關系,如圖:

用xib建立一個UIView(xib自定義view,修改不了frame的問題)

3.2 在修改xib 的 Simulated Metrics 的參數值,即使view的大小可自動變化,如圖:

用xib建立一個UIView(xib自定義view,修改不了frame的問題)

4.使用xib代碼:

#import <UIKit/UIKit.h>

@interface CustomerView : UIView

+(instancetype)customerView;

@end
           
#import "CustomerView.h"

@implementation CustomerView

+(instancetype)customerView
{
    return [[[NSBundle mainBundle] loadNibNamed:@"CustomerView" owner:self options:nil] firstObject];
}

@end
           
//添加customerView
CustomerView *customerView = [CustomerView customerView];
customerView.frame = CGRectMake(, , kScreenWidth, kScreenHeight);
customerView.backgroundColor = [UIColor purpleColor];
[self.view addSubview:customerView];
           

注意:iOS用xib自定義view,修改不了frame的問題,主要是xib使用了autolayout布局頁面,造成設定frame無效,是以去掉xib的autolayout布局(xib中把Use Auto layout的勾去掉,找到Simulated Metrics , 把Size 設定成None, 沒有None就是Freeform)或者在drawRect中設定frame來解決(推薦後者),(例如:在UITableViewCell不能改變frame)

方法1:在“-(void)drawRect:(CGRect)rect”中設定:

frame明顯設定不對cell的高度為100,xib的view中width=100,height=80,明顯不對:

用xib建立一個UIView(xib自定義view,修改不了frame的問題)

下邊的frame才是正确的:

用xib建立一個UIView(xib自定義view,修改不了frame的問題)
-(void)drawRect:(CGRect)rect
{
    _customerView.frame = CGRectMake(, , , );
}
           

方法2:stackoverflow上網友答案:

用xib建立一個UIView(xib自定義view,修改不了frame的問題)