我正在我的应用程序中实现自动布局。我希望通过以编程方式使用自动布局将 UILabel 放置在距屏幕底部 20px 的位置。请帮助我解决我出错的地方。使用下面的代码,UILabel 在应用时不会显示底部约束。下面是我的代码。
lblSwipe=[[UILabel alloc]init];
lblSwipe.text=@"Swipe to learn more";
lblSwipe.textColor=[UIColor lightGrayColor];
lblSwipe.textAlignment = NSTextAlignmentCenter;
lblSwipe.backgroundColor=[UIColor yellowColor];
lblSwipe.font=[UIFont systemFontOfSize:14.0];
[self.view addSubview:lblSwipe];
[lblSwipe setTranslatesAutoresizingMaskIntoConstraints:NO];
//to position UILabel in centre of the screen
NSLayoutConstraint *myConstraint=[NSLayoutConstraint
constraintWithItem:lblSwipe
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
[self.view addConstraint:myConstraint];
//to apply a fixed width of 300 to UILabel
[lblSwipe addConstraint:[NSLayoutConstraint constraintWithItem:lblSwipe
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:300.0]];
//to place UILabel 20px above from bottom of the screen
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:lblSwipe
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:20.0]];
最佳答案
底部约束的常量必须为 -20(因为上面表示负偏移)。
关于ios - 如何以编程方式对 UILabel 应用约束,使其位于 Objective C 中 View 底部上方 20px,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28455212/