2016-04-30 74 views
0

我有一个名为CustomRectangle的自定义UIView子类。我在ViewController中实例化它,并在ViewController中创建它的所有约束。我的目标是以编程方式在此UIView子类中创建所有约束。问题是我不知道如何在那里设置约束,因为我没有引用Storyboard中的任何其他视图。在UIView子类中添加编程约束的地方?

例如,如果我想我的观点CustomRectangle为中心基础上另一种看法,我会为其他视图中创建的视图控制器的@IBOutlet,然后用它来中心CustomRectangle。我不知道这是否可以在UIView子类中完成。

我想基于MVC(模型视图控制器)体系结构来做到这一点。

这是什么最佳做法?任何想法如何做到这一点?

+0

也许你可以重写方法'didMoveToSuperview:'并在那里创建约束条件 –

+0

我该怎么做?我的意思是如果我想以我的自定义视图为中心调用基于另一个视图的“CustomRectangle”,这是如何完成的?我不知道如何基于MVC构建这个。在CustomRectangle中的 – JEL

+0

给你的视图的约束 –

回答

0

你应该用initWithFrame方法CustomRectangle来做到这一点。

UIView's Subclass emample,

- (id)initWithFrame:(CGRect)frame{ 

self = [super initWithFrame: frame]; 

if (self) { 


    [self setFrame:CGRectMake(0, 0, 50, 50)]; 
    //add constraint here for example 

    [self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute: NSLayoutAttributeNotAnAttribute multiplier:1 constant:50]]; 

} 
return self; 
} 

在转换迅速,这是客观的C代码!!

希望这将有助于:)

+1

感谢您的回应!我如何设置这些约束相对于其他事情?不知道我是否有道理。基本上,如果我想将'CustomRectangle'限制在UIButton的底部,我不知道如何获得对该UIButton的引用,因为在这个UIView子类中所有东西都是孤立的。 – JEL

0

有一些事情你应该做的:

  1. 记得设置translatesAutoresizingMaskIntoConstraints = NO的约束工作。然而,如果你认为视图是自动布局的,在你的视图中你应该为你的子视图使用自动布局,并且实例化你的视图的视图应该为customRectangle(aka widht,alignment等)添加约束条件
  2. 在init方法中,你可以只需添加仅取决于您的视图的约束。其他限制应该从外部添加。

例如:

CustomRectangle *customRectangle = [[CustomRectangle *customRectangle alloc] init]; 
// just to be sure 
customRectangle.translatesAutoresizingMaskIntoConstraints = NO; 
// just as an example 
[self.view addConstraints[NSLayoutConstraint constraintWithItem:customRectangle attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0]]; 

希望它可以帮助!

+0

当你说“其他约束应该从外部添加”,这可能是一个'ViewController'?我正在'ViewController'中实例化'CustomRectangle',这是我为它放置约束的地方吗?如果是这样,你会把它放在'viewWillAppear'中? – JEL

+0

这取决于您使用的方法。例如,如果您的CustomRectangle是另一个View的子视图,则应该在该View的init方法中执行此操作。如果你在ViewController中做它,它取决于约束,但最好的地方可能是viewDidLoad。 – facumenzella