【问题标题】:autolayout view controller inheritance自动布局视图控制器继承
【发布时间】:2014-10-09 11:46:41
【问题描述】:

我有一个名为 LoginViewController 的 ViewController,它包含几个文本字段和一个按钮。

所有元素都可以很好地使用自动布局(以编程方式构建的规则),在这种情况下,元素以 X 为中心并带有其父视图。

现在,我想创建一个对 LoginViewController 犹豫不决的 UIViewController,称为 LeftLoginViewController。这个 LeftLoginViewController 和 LoginViewController 的功能一样,只是外观发生了变化,它应该支持父视图左侧的所有元素。

(这个 leftLoginViewController 是一个例子,我的问题是我应该如何管理我想在父亲的视图中移动视觉元素的情况)

完成此任务的最佳方法是什么?修改自动布局规则?因为显然你不能修改框架。

我应该为添加到 parentViewController 的主视图中的每个规则创建属性吗? LeftLoginViewController 可以修改它们的常量吗?如果我想将其中一条规则(例如 NSLayoutAttributeCenterX 更改为 NSLayoutAttributeTrailing)会发生什么情况,该属性是只读的。

对不起,我对此很困惑,我需要一些想法来获得正确的方向。

【问题讨论】:

    标签: ios autolayout xcode6


    【解决方案1】:

    如果LeftLoginViewController 的唯一区别是它的布局,则不需要子类。您可以使用类型初始化视图控制器。

    假设您使用的是 Objective-C:

    ViewController.h

    typedef NS_ENUM(NSUInteger, LayoutType) {
        LayoutTypeNormal,
        LayoutTypeLeft
    };
    
    @interface ViewController : UIViewController
    
    - (id)initWithLayoutType:(LayoutType)layoutType;
    
    @end
    

    ViewController.m

    @interface ViewController()
    
    @property (nonatomic) LayoutType layoutType;
    
    @end
    
    @implementation ViewController
    
    - (id)initWithLayoutType:(LayoutType)layoutType
    {
        self = [super init];
        if (self)
        {
            self.layoutType = layoutType;
        }
    
        return self;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        if (self.layoutType == LayoutTypeNormal)
        {
            // centre layout for normal
        }
        else if (self.layoutType == LayoutTypeLeft)
        {
            // left layout
        }
    }
    

    【讨论】:

    • 嗯,将所有元素向左移动只是一个例子,我的意思是如何实现从父亲视图控制器中移动元素
    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多