你可以这样实现:
在 MSSectionView.m 中:
#import "MSSectionView.h"
@implementation MSSectionView
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString: @"borderWidth"])
{
CGFloat borderWidth = [(NSNumber*)[change objectForKey:NSKeyValueChangeNewKey] floatValue];
[self setFrame: CGRectMake(borderWidth, borderWidth, self.frame.size.width/2 - (borderWidth * 3/2), self.frame.size.height/2 - (borderWidth * 3/2))];
}
else
{
[super observeValueForKeyPath: keyPath
ofObject: object
change: change
context: context];
}
}
@end
在 viewcontroller 中,它拥有一些 MSSectionView 作为子视图:
@implementation TSViewController
@synthesize borderWidth;
- (void) viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray* views = [self.view subviews];
for (UIView* subview in views)
{
if ([subview isKindOfClass: [MSSectionView class]])
{
MSSectionView* sectionView = (MSSectionView*) subview;
[self addObserver: sectionView
forKeyPath: @"borderWidth"
options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context: NULL];
}
}
}
在 viewcontroller.h 中:
@interface TSViewController : UIViewController
{
CGFloat borderWidth;
}
@property(nonatomic,readwrite,assign)CGFloat borderWidth;