简体   繁体   English

CGRectMake不起作用

[英]CGRectMake doesn't work

I'm working on example from "iOS Programming Cookbook", based on iOS 7. I need to create UITextField and add it to ViewController . 我正在研究基于iOS 7的“ iOS编程指南”中的示例。我需要创建UITextField并将其添加到ViewController

In ViewController.m I have: ViewController.m我有:

- (void) viewDidLoad {
    [super viewDidLoad];
    [self createField];  
}

- (void) createField {
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(20.0f, 35.0f, 280.0f, 30.0f)];
    self.textField.translatesAutoresizingMaskIntoConstraints = NO;
    self.textField.borderStyle = UITextBorderStyleRoundedRect;
    self.textField.placeholder = @"Enter text to share";
    self.textField.delegate = self;
    [self.view addSubview:self.textField];
}

On screenshot from book textField appears in the middle of screen's width under the status bar, but when I run it textField appears on the top left corner of screen behind the status bar. 在本书的屏幕快照上, textField出现在状态栏下方屏幕宽度的中间,但是当我运行它时, textField出现在状态栏下方屏幕的左上角。

Maybe the problem is, that I run app on iPhone 6 simulator with iOS 8. But I don't know how to solve it. 可能的问题是,我在装有iOS 8的iPhone 6模拟器上运行应用程序。但是我不知道如何解决它。

Thanks! 谢谢!

Using self.textField.translatesAutoresizingMaskIntoConstraints = NO; 使用self.textField.translatesAutoresizingMaskIntoConstraints = NO; is pretty much telling the object that it doesn't really care about the frame but relies more on the constraints that you give it. 几乎告诉对象它并不真正在乎框架,而是更多地依赖于您赋予它的约束。 Setting it to YES takes the frame and automatically applies constraints to it to mimic the frame that you give it. 将其设置为YES将获取框架并自动对其施加约束以模仿您提供的框架。

For example it would apply the constraints to have the frame appear at: CGRectMake(20.0f, 35.0f, 280.0f, 30.0f) . 例如,它将应用约束以使帧出现在: CGRectMake(20.0f, 35.0f, 280.0f, 30.0f) When setting it to NO use NSLayoutConstraint and create the constraints programatically. 将其设置为NO使用NSLayoutConstraint并以编程方式创建约束。

But in your case just remove the line 但是在您的情况下,只需删除行

self.textField.translatesAutoresizingMaskIntoConstraints = NO;

because it is set to YES by default. 因为默认情况下它设置为YES

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM