ios - 如何以编程方式对 UILabel 应用约束,使其位于 Objective C 中 View 底部上方 20px

标签 ios objective-c iphone autolayout

我正在我的应用程序中实现自动布局。我希望通过以编程方式使用自动布局将 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/

相关文章:

ios - 检测主线程之外的 UI 操作

ios - 在 Swift 3 中使用 Firebase 对 OneSignal 进行身份验证以将自动通知发送到分段

ios - iPad 上的 UIActivityViewController 在 iOS 8 中忽略 "modal view"

ios - 使用 Realm 和 circleCI(使用 Carthage)构建失败

objective-c - XCode 4,签名无效 (-19011)

objective-c - 将 UIPopoverController 呈现在同一位置,仅更改箭头偏移量

ios - 谁能帮我解决这个 xcode 问题?

objective-c - 何时使用 InterfaceBuilder 构建 View ?

iphone - If 语句在第一次运行时不检查条件

iphone - iPhone 应用程序中的收件人栏