您不能像这样编辑框架:
textField.frame.origin.y -= kOFFSET_FOR_KEYBOARD;
textField.frame.size.height += kOFFSET_FOR_KEYBOARD;
您需要获取框架,对其进行编辑,然后再次将其分配回来,如下所示:
CGRect myFrame = textField.frame;
myFrame.origin.y -= kOFFSET_FOR_KEYBOARD;
myFrame.size.height += kOFFSET_FOR_KEYBOARD;
textField.frame = myFrame;
如果您发现自己必须经常这样做,您可以编写一个类别来实现这些方法(setHeight、setX...),例如:
#import <UIKit/UIKit.h>
@interface UIView (AlterFrame)
- (void) setFrameWidth:(CGFloat)newWidth;
- (void) setFrameHeight:(CGFloat)newHeight;
- (void) setFrameOriginX:(CGFloat)newX;
- (void) setFrameOriginY:(CGFloat)newY;
@end
#import "UIView+AlterFrame.h"
@implementation UIView (AlterFrame)
- (void) setFrameWidth:(CGFloat)newWidth {
CGRect f = self.frame;
f.size.width = newWidth;
self.frame = f;
}
- (void) setFrameHeight:(CGFloat)newHeight {
CGRect f = self.frame;
f.size.height = newHeight;
self.frame = f;
}
- (void) setFrameOriginX:(CGFloat)newX {
CGRect f = self.frame;
f.origin.x = newX;
self.frame = f;
}
- (void) setFrameOriginY:(CGFloat)newY {
CGRect f = self.frame;
f.origin.y = newY;
self.frame = f;
}
@end
取自第二个响应:
改变 CGRect (或任何结构)?