[英]Set a variable equal to a view's frame without the value changing when view's frame changes
[英]How to change the frame of a view when a variable value changes?
在我的视图控制器中,视图很少。 该视图的所有框架均取决于变量
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) ) ];
我想改变秒-1的帧时i的值更改borderwidth
从另一个类。 我们该怎么做? 我知道
[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。 所以我不能用这种方法为所有这些设置框架。
您可以这样实现:
在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;
为了实现这一目标,需要一个for循环并更改所有帧。
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) )];
}
您可以考虑使用KVO。 在sec1
类中观察borderWidth
的变化。 这样,如果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.
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.