扫码关注官方订阅号
控制器自带一个view,我想用自定义的view,替换控制器原生的view,自定义的customview,已经写好了,在load,或者iniltlize写好像都不行,就是让self。view 是我自定义的customview,在哪个方法写呢?initWithframe?
走同样的路,发现不同的人生
你用代码实现的话,可以写在 loadView 里,但是不要调 super
- (void)loadView { self.view = [[CustomView alloc] init]; ... }
用 IB 的话,选中 controller 的 view ,在右边改它的 Class 为你的 CustomView
IB
controller
view
Class
CustomView
需要在Storyboard中把UIView的类名修改为你自定义的类名:点击位于Storyboard的CustomView,在右侧的选项卡中,点击Identity Inspector选项卡,然后修改Custom Class;
然后把这个CustomView从Storyboard中拖到ViewController中,建立IBOutlet;
IBOutlet
这样你就拥有了这个CustomView的实例了,然后就可以修改它的属性,调用它的方法。
#import "ViewController.h" #import "UIDashedLine.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIDashedLine *customView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 方法1: 完全由代码添加自定义的View CGRect lineBounds = CGRectMake(0, 22, self.view.bounds.size.width, 22); UIDashedLine *line = [[UIDashedLine alloc] initWithFrame:lineBounds withStrokeColor:[UIColor greenColor]]; [self.view addSubview:line]; // 方法2: 在Storyboard中添加一个UIView,在Identity Inspector 把Custom Class设置为你自定义View的类名 self.customView.strokeColor = [UIColor yellowColor]; self.customView.segmentsLength = 2; } @end
可以参考这个demo工程https://github.com/li2/Learning_iOS_Programming/tree/master/CustomView
如果你是想通过Storyboard来完成这件事情,就用不着initWithframe,这个方法的目的是用代码生成一个指定frame的view。
initWithframe
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
扫描下载App
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
你用代码实现的话,可以写在 loadView 里,但是不要调 super
用
IB
的话,选中controller
的view
,在右边改它的Class
为你的CustomView
需要在Storyboard中把UIView的类名修改为你自定义的类名:点击位于Storyboard的CustomView,在右侧的选项卡中,点击Identity Inspector选项卡,然后修改Custom Class;
然后把这个CustomView从Storyboard中拖到ViewController中,建立
IBOutlet
;这样你就拥有了这个CustomView的实例了,然后就可以修改它的属性,调用它的方法。
可以参考这个demo工程
https://github.com/li2/Learning_iOS_Programming/tree/master/CustomView
如果你是想通过Storyboard来完成这件事情,就用不着
initWithframe
,这个方法的目的是用代码生成一个指定frame的view。