ios - controller 自带的view,用自定义的view替换自带的view,用代码在怎么写?
怪我咯
怪我咯 2017-04-17 16:37:48
[iOS讨论组]

控制器自带一个view,我想用自定义的view,替换控制器原生的view,自定义的customview,已经写好了,在load,或者iniltlize写好像都不行,就是让self。view 是我自定义的customview,在哪个方法写呢?initWithframe?

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
PHPz

你用代码实现的话,可以写在 loadView 里,但是不要调 super

- (void)loadView
{
    self.view = [[CustomView alloc] init];
    ...
}

IB 的话,选中 controllerview ,在右边改它的 Class 为你的 CustomView

巴扎黑
  • 需要在Storyboard中把UIView的类名修改为你自定义的类名:点击位于Storyboard的CustomView,在右侧的选项卡中,点击Identity Inspector选项卡,然后修改Custom Class;

  • 然后把这个CustomView从Storyboard中拖到ViewController中,建立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。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号