iOS 使用xib定义一个View,修改frame无效问题解决
遇到过好多次使用自定义view,修改frame无效问题, 之前都是放弃xib,直接手写,发现手写简单的还行,复杂的UI就坑逼了。所以还是需要用到可视化编辑的xib。
整理一下,自己备忘也供iOS开发的朋友参考:
一般我们会直接这样写:
1 2 3 4 | XPGovRecUnitView *recUnitView = [[[ NSBundle mainBundle] loadNibNamed:@ "XPGovRecUnitView" owner: self options: nil ] firstObject]; recUnitView.tag = 10000+i; recUnitView.delegate = self ; recUnitView.frame = CGRectMake(i*89, 0, 89, 139); |
这是我一个项目中的代码,但是这样出现了一个问题就是iPhone 6,6Plus以上的正常, iPhone5s屏幕尺寸的就显示不正常了。
使用
UIView *recUnitView = [[UIView alloc] initWithFrame:CGRectMake(i*89, 0, 89, 139)];
调试后发现,使用alloc的方式iPhone5也是正常的。但是这样就要手写代码,往这个UIView 添加控件
解决方案:
1. 先把 XPGovRecUnitView.xib这个xib文件的属性设置一下
在右侧属性栏中,
找到Interface Builder Document , 把Use Auto layout的勾去掉
找到Simulated Metrics , 把Size 设置成None, 没有None就是Freeform
2.修改XPGovRecUnitView.m代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #import "XPGovRecUnitView.h" @interface XPGovRecUnitView () { CGRect tempframe; } @end @implementation XPGovRecUnitView -( id )initWithFrame:(CGRect)frame { self = [ super initWithFrame:frame]; if ( self ) { NSArray *nibs=[[ NSBundle mainBundle]loadNibNamed:@ "XPGovRecUnitView" owner: nil options: nil ]; self =[nibs objectAtIndex:0]; tempframe = frame; [ self initSubViews]; } return self ; } -( void )drawRect:(CGRect)rect { self .frame = tempframe; } @end |
3.使用时代码
1 2 3 | XPGovRecUnitView *recUnitView = [[XPGovRecUnitView alloc] initWithFrame:CGRectMake(i*89, 0, 89, 139)]; recUnitView.tag = 10000+i; recUnitView.delegate = self ; |
这样就正常了。
专注iOS、Golang开发。
技术博客:http://xiaopin.cnblogs.com
分类:
iOS 常用小知识点
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?