[英]Creating AutoLayout Constraints programmatically (IOS) Xcode 7.0.1
我看过几个关于这个话题的问题; 然而,他们都没有解决这个问题,而对于我的生活,我无法弄清楚为什么约束没有生效。 (也许是因为我有一段时间没有睡觉......我知道这会适得其反)。
我是IOS开发的新手,但我很努力,也很快学习。 如果你可以提供一个解释,说明为什么我的原始代码不起作用,这将是非常有用的。 赞成谁能解决问题!
好的,所以我正在开发一个我实际上已经工作了很长一段时间的应用程序,当我刚开始时,我做了一个非常草率的工作。 所以我基本上重建应用程序的代码,但完全删除了Interface Builder(Storyboard)。 我试图在本地将UIBut引脚化为UIVut(我宁愿不在全局声明它)。
// parentView初始化//
parentView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
[parentView setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:parentView];
parentView.tag = 0;
// homeScreenView已初始化//
homeScreenView=[[UIView alloc]initWithFrame:CGRectMake(0, homeScreenTitle.frame.size.height, screenWidth, screenHeight-homeScreenTitle.frame.size.height-height)];
[homeScreenView setBackgroundColor:[UIColor greenColor]];
[parentView addSubview:homeScreenView];
homeScreenView.tag = 2;
// chatMenuView初始化//
chatMenuView=[[UIView alloc]initWithFrame:CGRectMake(0, homeScreenTitle.frame.size.height+10, 100, screenHeight-height-10-10-homeScreenTitle.frame.size.height)];
[chatMenuView setBackgroundColor:[UIColor grayColor]];
[parentView addSubview:chatMenuView];
chatMenuView.tag = 3;
// chatMenuButton已初始化//
chatMenuButton = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *buttonText = [NSString stringWithFormat:@"CHAT"];
[chatMenuButton setTitle:buttonText forState:UIControlStateNormal];
[parentView addSubview:chatMenuButton];
[chatMenuButton sizeToFit];
chatMenuButton.center = CGPointMake(0,screenHeight/2);
UIImage *chatIcon = [UIImage imageNamed:@"GrayHouse1.png"];
[chatMenuButton setBackgroundImage:chatIcon forState:(UIControlStateNormal)];
chatMenuButton.tag = 5;
// pinChatButton //
NSLayoutConstraint *pinChat = [NSLayoutConstraint constraintWithItem:chatMenuView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:chatMenuButton
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:0];
[self.view addConstraint: pinChat];
我还想补充一点,所有这些代码都在viewDidLoad方法中,并且所有其他视图都在头文件中声明(如IBOutlets)。基本上,当我运行代码时,UIView前导边距位于x = 100处,按钮位于x = 0的位置,这是在添加约束之前的假设,也应该将按钮移动到位置x = 100。
所以我基本上重建应用程序的代码,但完全删除了Interface Builder(Storyboard)
首先 - 你真的在这里逆潮流游泳。 每个人都使用Interface Builder进行基本布局,因为可视化布局,并在可视化编辑器中查看约束更容易。 当你尝试做一些聪明的事情时,你应该真正保存代码生成的约束。 更不用说设置标签的所有代码等等。
已经得到了这一点的方式,您的约束不作一大堆的道理给我-你在限制的主要空间chatMenuView
等于的尾随空格chatMenuButton
。 我可以想象这会有用的场景,但你可能想要的更像是:
NSLayoutConstraint *pinChat = [NSLayoutConstraint constraintWithItem:chatMenuButton
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:chatMenuView
attribute:NSLayoutAttributeLeading
multiplier:1
constant:100];
最后,即使你确定要在代码中创建的约束,可以考虑使用可视化格式 ,这至少在一定程度可读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.