当前位置: 动力学知识库 > 问答 > 编程问答 >

objective c - How to make UIView subclass's frame immutable ouside

问题描述:

I want to write an UIView's subclass whose frame is immutable outside(e.g. UIPickerView,UISwitch).So I try to override layoutSubviews,sizeToFit and setFrame,but not working.

Who knows how to implement it like UIKit's UIPickerView or UISwitch,thanks.

Update:

- (void)setFrame:(CGRect)frame

{

[super setFrame:frame];

self.frame = CGRectMake(0, 0, 200, 200);

}

I cannot set the view's frame using _frame,so when I write these,I will enter a endless loop.

网友答案:

Override -setBounds: to constrain your view to a given bounds.

Something like this should work:

static CGFloat maxHeight = ...;
static CGFloat maxWidth  = ...;

- (void)setBounds:(CGRect)bounds {
   CGSize size = bounds.size; 
   size.width = MIN(maxWidth, size.width);
   size.height = MIN(maxHeight, size.height);

   bounds.size = size;
   [super setBounds:bounds];
}
网友答案:

self.frame = newFrame is essentially the same as calling [self setFrame:newFrame], that's why it enters an endless loop.

However you can just do it like that:

- (void)setFrame:(CGRect)frame        
{
    [super setFrame:CGRectMake(0, 0, 200, 200)];
}

Note that this sets the anchor point (top left corner) to (0,0) which might not be what you intend. Use setBounds: instead or pass the origin along to super:

- (void)setFrame:(CGRect)frame        
{
    [super setFrame:CGRectMake(frame.origin.x, frame.origin.y, 200, 200)];
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: