IOS學習筆記(五)之視圖的層次結構,查找,常用屬性與清理學習(部落格位址:http://blog.csdn.net/developer_jiangqq)
Author:hmjiangqq
Email:[email protected]
(一):視圖的層次結構
1.UIView層次結構可以了解為"視圖樹"-View Hierarchy
2.一個視圖就是一個容器,當一個視圖包含其他視圖的時候,兩個視圖之間就建立了
一個父子複習。被包含的視圖被稱為"子視圖(subview)",包含的視圖稱為“父視圖或”
超視圖(superview)"
3.從視覺上看,子視圖隐藏了俯視圖的内容,設定透明屬性可以看到父視圖的内容
4.每個父視圖都有一個有序的數組存儲着它的子視圖,存儲的順序就會影響到每個子視圖
的顯示效果,比如:兩個兄弟視圖重疊在一起,後來被加入的視圖就會出現在另外視圖的上面
5.一個視圖可以嵌入多個subview,但是隻能有一個superview
視圖的常用方法
當調用addSubView的時候,會對其進行保留,相當于retain了一個對象,當調用removeFromSuperView時候
會進行釋放該對象,相當于release了該對象
基本的添加和删除子視圖的方法
- (void)removeFromSuperview;
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;
- (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2;
- (void)addSubview:(UIView *)view;
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;
- (void)bringSubviewToFront:(UIView *)view;
- (void)sendSubviewToBack:(UIView *)view;
執行個體代碼:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
UIView *view1=[[UIView alloc]initWithFrame:CGRectMake(60, 100, 200, 100)];
view1.backgroundColor=[UIColor redColor];
[self.window addSubview:view1];
[view1 release];
UIView *view2=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
view2.backgroundColor=[UIColor blueColor];
[self.window addSubview:view2];
[view2 release];
NSLog(@"view1 superview:%@",[view1 superview]);
NSLog(@"view2 superview:%@",[view2 superview]);
NSLog(@"self.window subViews:%d",[[self.window subviews]count]);
return YES;
}
運作截圖:
(二):視圖的查找
1.UIView類中又一個tag屬性,通過這個tag屬性可以标示一個視圖對象(整數)
2.擷取的方法,viewWithTag:方法來檢索标示過的子視圖:
[注]:如果tag值不設定,預設的tag值為0;
設定和查找方法代碼如下:
UIView *view3=[[UIView alloc]initWithFrame:CGRectMake(60, 250, 200, 100)];
view3.tag=100;
view3.backgroundColor=[UIColor yellowColor];
[self.window addSubview:view3];
[view3 release];
NSLog(@"view3:%@",view3);
//通過tag值查找view
UIView *myView=[self.window viewWithTag:100];
myView.alpha=0.1;
NSLog(@"myView:%@",myView);
return YES;
運作截圖:
(三):常用屬性:
1.alpha //透明度
2.backgroundColor //背景顔色
3.subViews //子視圖集合
4.hidden //是否隐藏
5.tag //标簽紙
6.superview //父視圖
7.multipleTouchEnabled //是否開啟多點觸摸
8.userInteractionEnabled //是否響應觸摸事件
(四)自定義UIView
繼承UIView,建立對象
(五)視圖對象的清理
如果手動建立一個視圖,配置設定了任何記憶體,存儲了了任何對象的引用,都需要釋放資源,
必須實作dealloc方法。當某個對象的引用計數為0,系統會調用其dealloc方法去釋放對象資源
切記不要手動調用dealloc方法
-(void)dealloc{
//釋放自定義對象
[super dealloc];
}