在我的viewcontroller中,视图很少。所有视图的帧都取决于变量
CGFloat borderWidth
这些视图定义为
sec1 = [[MSSectionView alloc]initWithFrame:CGRectMake(self.borderWidth, self.borderWidth,self.frame.size.width/2-(self.borderWidth*3/2),self.frame.size.height/2 - (self.borderWidth*3/2) ) ];
当我从另一个类更改borderwidth
的值时,我想更改sec1的帧。
我们怎么能这样做?
我知道
[sec1 setFrame:CGRectMake(self.borderWidth, self.borderWidth,self.frame.size.width/2-(self.borderWidth*3/2),self.frame.size.height/2 - (self.borderWidth*3/2) )];
会更改框架,但有很多uiviews。所以我不能在这个方法中为所有这些设置框架。
答案 0 :(得分:1)
你可以这样实现:
在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;
答案 1 :(得分:0)
为实现这一目标,请采用一个循环并更改所有帧。
for(UIView *subview in yourview.subviews)
{
// Here you can change your frames based on the condition
//here you will get old frame value of subview so you can change by using the old frame values of all the subviews.
[subview setFrame:CGRectMake(self.borderWidth, self.borderWidth,self.frame.size.width/2-(self.borderWidth*3/2),self.frame.size.height/2 - (self.borderWidth*3/2) )];
}
答案 2 :(得分:0)
您可以考虑使用KVO。观察borderWidth
课程中sec1
的更改。这样,如果borderWidthe
发生变化,您的sec1
课程就会相应更改。
- (void)viewDidLoad
{
[super viewDidLoad];
[self addObserver:self forKeyPath:@"borderWidth" options:NSKeyValueObservingOptionNew context:&self->borderWidth];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == &self.borderWidth) {
if ([keyPath isEqualToString:@"borderWidth"]) {
// Calculate your subview's frame.
}
}
}