我看到了几个关于这个话题的问题,但是没有一个解决了这个问题,而且我再怎么想也想不出为什么限制不起作用(也许是因为我很久没有睡觉了… 我知道这是适得其反的)。
我是IOS开发的新手,但我很努力地学习。如果您能解释一下为什么我的原始代码不起作用,那将非常有帮助。谁能解决这个问题就点个赞吧!
好的,我正在开发一个应用程序,实际上我已经在开发这个应用程序相当长的时间了,但我一开始做得非常粗糙。所以我基本上在完全削减Interface Builder (Storyboard)的情况下重建了应用程序的代码。我试图将一个UIButton局部固定到一个UIView上(我宁愿不将其全局声明)。
//parentView 初始化//
我是IOS开发的新手,但我很努力地学习。如果您能解释一下为什么我的原始代码不起作用,那将非常有帮助。谁能解决这个问题就点个赞吧!
好的,我正在开发一个应用程序,实际上我已经在开发这个应用程序相当长的时间了,但我一开始做得非常粗糙。所以我基本上在完全削减Interface Builder (Storyboard)的情况下重建了应用程序的代码。我试图将一个UIButton局部固定到一个UIView上(我宁愿不将其全局声明)。
//parentView 初始化//
parentView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
[parentView setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:parentView];
parentView.tag = 0;
// 主屏幕视图已初始化 //
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=[[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 = [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的leading margin处于x = 100的位置,而按钮处于x = 0的位置,这是在添加约束之前应该处于的位置,添加约束后应该将按钮移动到x = 100的位置。