用xib建立一個UIView(xib自定義view,修改不了frame的問題)
阿新 • • 發佈:2019-01-26
1.建立一個CustomerView的檔案,commend+n,如圖:
2.用xib建立一個view,命名為CustomerView,commend+n,如圖:
3.修改xib中如下資料,
3.1 首先修改Custom Class中的Class為:CustomerView,即建立與CustomerView的關聯關係,如圖:
3.2 在修改xib 的 Simulated Metrics 的引數值,即使view的大小可自動變化,如圖:
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(0, 0, 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,明顯不對:
下邊的frame才是正確的:
-(void)drawRect:(CGRect)rect
{
_customerView.frame = CGRectMake(50, 30, 100, 50);
}
方法2:stackoverflow上網友答案: