不使用xib ,纯代码开发的过程中,动态UI 需要改对象的大小位置 反复使用CGRectMake 去 setFrame 非常低效耗时,而且 牵一发动全身.
以下整理出几个方法,方便动态布局
1.set 方法 重新布局
#import <Foundation/Foundation.h> @interface HuofarUtils : NSObject @end CGRect CGRectSetWidth(CGRect rect, CGFloat width); CGRect CGRectSetHeight(CGRect rect, CGFloat height); CGRect CGRectSetSize(CGRect rect, CGSize size); CGRect CGRectSetX(CGRect rect, CGFloat x); CGRect CGRectSetY(CGRect rect, CGFloat y); CGRect CGRectSetOrigin(CGRect rect, CGPoint origin); #import "HuofarUtils.h" @implementation HuofarUtils @end CGRect CGRectSetWidth(CGRect rect, CGFloat width) { return CGRectMake(rect.origin.x, rect.origin.y, width, rect.size.height); } CGRect CGRectSetHeight(CGRect rect, CGFloat height) { return CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, height); } CGRect CGRectSetSize(CGRect rect, CGSize size) { return CGRectMake(rect.origin.x, rect.origin.y, size.width, size.height); } CGRect CGRectSetX(CGRect rect, CGFloat x) { return CGRectMake(x, rect.origin.y, rect.size.width, rect.size.height); } CGRect CGRectSetY(CGRect rect, CGFloat y) { return CGRectMake(rect.origin.x, y, rect.size.width, rect.size.height); } CGRect CGRectSetOrigin(CGRect rect, CGPoint origin) { return CGRectMake(origin.x, origin.y, rect.size.width, rect.size.height); }
2. Get 方法 获取
CGRectGetHeight /Width /X/ Y 系统自带
3. 以UILabel 为例 获取动态高度 或 宽度
(1)宽度固定 获取 lab 动态高度
- (CGFloat)heightForTitle:(NSString *)title {//momentWith 静态宽度 CGRect tmpRect = [title boundingRectWithSize:CGSizeMake(momentWidth, 2000) options:NSStringDrawingUsesLineFragmentOrigin //可选的计算参考条件 attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:16],NSFontAttributeName, nil] context:nil]; return tmpRect.size.height; }
(2)高度固定获取 lab 动态宽度
- (CGFloat)widthForTitle:(NSString *)title { NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:16]}; CGSize size = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, 30) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size; return size.width ; }
以上两个方法都差不多 就是看谁恒定 另一个就是动态得到的value
时间: 2024-10-14 07:39:48