6.1 View Hierarchies
确实代码很妙,
// Recursively travel down the view tree, increasing the
// indentation level for children
- (void) dumpView: (UIView *) aView atIndent: (int) indent into: (NSMutableString *) outstring
{
// Add the indentation
for (int i = 0; i < indent; i++)
[outstring appendString:@"--"];
// Add the class description
[outstring appendFormat:@"[%2d] %@\n", indent,
[[aView class] description]];
// Recurse on subviews
for (UIView *view in aView.subviews)
[self dumpView:view atIndent:indent + 1 into:outstring];
}
// Start the tree recursion at level 0 with the root view
- (void) dumpTree: (id) sender
{
NSMutableString *outstring = [NSMutableString string];
[self dumpView:self.view atIndent:0 into:outstring];
NSLog(@"%@", outstring);
}
The subviewsmethod returns just those views that are immediate children of a givenview
A call to[[UIApplication sharedApplication] windows]returns the array of application windows.
Theview’s windowproperty points to the window that owns it.
TheisDescendantOfView:method determines whether a view lives within another view,even if that view is not its direct superview.
6.3 Managing Subviews
Adding Subviews
ninsertSubview:atIndex:
ninsertSubview:aboveSubview:
ninsertSubview:belowSubview:
viewWithTag 这个方法很好用,因为这个查找是一个递归的查找,不需要查找结果是直接的子视图。因此直接用window即可,
UILabel *label = (UILabel *)[self.view.window viewWithTag:101];
label.text = @"Hello World";
UIView的这个TagExtensions 很好,底下是用法。
-
- (IBAction)updateTime:(id)sender{
// set the label to the current time[self.view.window labelWithTag:LABEL_TAG].text =
[[NSDate date] description];
}
-
- (IBAction)updateSwitch:(id)sender{
// toggle the switch from its current setting
UISwitch *s = [self.view.window switchWithTag:SWITCH_TAG];[s setOn:!s.isOn];}
@interface UIView (TagExtensions)
- (UILabel *) labelWithTag: (NSInteger) aTag;- (UISwitch *) switchWithTag: (NSInteger) aTag;@end