为什么我的UITextView会在我使用frame属性时显示,但在我使用约束时却不会显示?

时间:2013-01-16 18:10:40

标签: ios objective-c xcode constraints autolayout

我是新手使用约束,所以我不会感到惊讶我有什么不对劲,但我无法弄清楚我做了什么和/或如何解决它。

这是我使用frame属性的方法;它工作正常,文本视图显示:

-(void)displayFeedbackText {
    feedback = [[UITextView alloc] init];
    feedback.backgroundColor = [UIColor clearColor];
    feedback.font = [UIFont fontWithName:@"Helvetica Neue" size:14];
    NSString *t = @"If you have any problems with the" + 16; //Longest line of text view + padding.
    float textWidth = [t sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:14]].width;
    float textHeight = [t sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:14]].height;
    feedback.text=@"Thank you for buying My Haiku! \nIf you have any problems with the \napp, or if you want to share any \nthoughts or suggestions, please \nemail me at joel@xxxxx.com.";
    feedback.editable=NO;
    feedback.frame = CGRectMake(screenWidth/2-textWidth/2, (screenHeight/2-tabBarHeight) - (textHeight*6)/2, textWidth, textHeight*6);
    feedback.dataDetectorTypes=UIDataDetectorTypeAll;
    [self.view addSubview:feedback];
}

以下是使用约束的方法(我在self.view.translatesAutoresizingMaskIntoConstraints中将NO设置为viewDidLoad。什么都没有出现:

-(void)displayFeedbackText {
    feedback = [[UITextView alloc] init];
    feedback.backgroundColor = [UIColor clearColor];
    feedback.font = [UIFont fontWithName:@"Helvetica Neue" size:14];
    feedback.text=@"Thank you for buying My Haiku! \nIf you have any problems with the \napp, or if you want to share any \nthoughts or suggestions, please \nemail me at joel@xxxxx.com.";
    feedback.editable=NO;
    feedback.dataDetectorTypes=UIDataDetectorTypeAll;
    NSLayoutConstraint *constraintX = [NSLayoutConstraint constraintWithItem:feedback attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    NSLayoutConstraint *constraintY = [NSLayoutConstraint constraintWithItem:feedback attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
    [self.view addConstraint:constraintX];
    [self.view addConstraint:constraintY];
    [self.view addSubview:feedback];
}

我做错了什么以及如何解决?

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

我认为它没有显示,因为你没有尺寸限制,所以它的大小可能为零。尝试设置显式大小约束或相对于superview的约束。如果它们是明确的约束,那么你就这样做(并且类似于高度约束):

NSLayoutConstraint *widthCon = [NSLayoutConstraint constraintWithItem:feedback attribute:NSLayoutAttributeWidth relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1  constant:320];
[feedback addConstraint:widthCon];