2016-04-30 38 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

相關問題