【问题标题】:Where to add programmatic constraints in UIView subclass?在 UIView 子类中在哪里添加编程约束?
【发布时间】:2016-08-25 07:24:17
【问题描述】:

我有一个名为 CustomRectangle 的自定义 UIView 子类。我在 ViewController 中实例化它并在 ViewController 中创建它的所有约束。我的目标是以编程方式在这个 UIView 子类中创建所有约束。问题是我不知道如何在那里设置约束,因为我没有参考情节提要中的任何其他视图。

例如,如果我希望我的视图 CustomRectangle 基于另一个视图居中,我将在 ViewController 中为另一个视图创建一个 @IBOutlet,然后使用它来居中 CustomRectangle。我不知道这是否可以在 UIView 子类中做到。

我想基于MVC(模型视图控制器)架构来做这个。

这方面的最佳做法是什么?关于如何做到这一点的任何想法?

【问题讨论】:

  • 也许你可以重写 didMoveToSuperview: 方法并在那里创建约束
  • 我该怎么做?我的意思是,如果我想基于另一个视图将名为CustomRectangle 的自定义视图居中,这是如何完成的?我不确定如何基于 MVC 来构建它。
  • 在 CustomRectangle 中为您的视图提供约束
  • @PKT 不确定如何。能给个例子或教程吗?谢谢

标签: ios cocoa-touch model-view-controller uiview


【解决方案1】:

你应该做几件事:

  1. 请记住设置 translatesAutoresizingMaskIntoConstraints = NO 以使约束起作用。但是,如果您认为视图是自动布局方式,那么在您的视图中,您应该对子视图使用自动布局,并且实例化您的视图的视图应该为 customRectangle 添加约束(也就是宽度、对齐等)
  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]];

希望对你有帮助!!

【讨论】:

  • 当您说“应从外部添加其他约束”时,这可能是ViewController?我在ViewController 中实例化CustomRectangle,这是我要为它设置约束的地方吗?如果是,你会把它放在viewWillAppear 的哪里?
  • 这取决于您使用的方法。例如,如果您的 CustomRectangle 是另一个 View 的子视图,您应该在该 View 的 init 方法中执行此操作。如果您在 ViewController 中执行此操作,则取决于约束,但可能最好的位置是在 viewDidLoad 中。
【解决方案2】:

您应该使用CustomRectangleinitWithFrame 方法来执行此操作。

例如UIView's Subclass

- (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 代码!!

希望这会有所帮助:)

【讨论】:

  • 感谢您的回复!如何相对于其他事物设置这些约束?不确定我是否有意义。基本上,如果我希望将“CustomRectangle”限制在 UIButton 的底部,我不知道如何获取对该 UIButton 的引用,因为所有内容都在这个 UIView 子类中被隔离。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
相关资源
最近更新 更多