UIButton设置框不工作



我已经为我的应用程序编写了以下代码:

self.PlayButton = [[UIButton alloc] init];
//Setup Play Button
[self.PlayButton setTranslatesAutoresizingMaskIntoConstraints:NO];
self.PlayButton.frame = CGRectMake(self.view.frame.size.width * 0.38, self.view.frame.size.height * 0.666, self.view.frame.size.width * 0.48, self.view.frame.size.height * 0.29);
[self.PlayButton setBackgroundImage:[UIImage imageNamed:@"PlayButton.png"] forState:UIControlStateNormal];
[self.PlayButton.layer setMagnificationFilter:kCAFilterNearest];
[self.PlayButton addTarget:self action:@selector(PlayButtonMethod) forControlEvents:(UIControlEvents)UIControlEventTouchUpInside]

[self.view addSubview:self.PlayButton];

但是,当这个代码运行时,它不会将图像显示在某个特定的位置,而是简单地显示在视图的左上角。几乎就像设置了

self.PlayButton.frame = CGRectMake(0, 0, self.view.frame.size.width * 0.48, self.view.frame.size.height * 0.29);

这很奇怪,因为宽度和高度输入正确,但无论出于何种原因,CGRectMake设置的按钮位置都没有被考虑在内。我对在代码中创建UIButtons做了一些研究,据我所见,这种情况不仅发生在代码编写的其他人身上,而且没有人完全负责。

如有任何帮助,我们将不胜感激。感谢

看起来我找到了修复程序:删除这行代码为我修复了问题。

[self.PlayButton setTranslatesAutoresizingMaskIntoConstraints:NO];

不能100%确定为什么这会导致问题,但它解决了问题。

使用标准alloc init方法创建UIButton时,实际上并没有创建按钮。用于创建和初始化UIButton的方法被称为buttonWithType:。这将创建指定类型的UIButton。如果使用alloc init,它将无法正常工作,请参阅UIButton的Apple文档。

所以你需要更改线路

self.PlayButton = [[UIButton alloc] init];

self.PlayButton = [UIButton buttonWithType:UIButtonTypeCustom];

buttonWithType:允许您传入UIButtonType的枚举,因此它将接受以下任何值:

  • UIButtonTypeCustom
  • UIButtonTypeSystem
  • UIButtonTypeDetailDisclosure
  • UIButtonTypeInfoLight
  • UIButtonTypeInfoDark
  • UIButtonTypeContactAdd
  • UIButtonTypeRoundedRect

如果你不给它传递UIButtonType,按钮将不会初始化,因为它不知道你想要什么类型的按钮,也不会假设。还可以查看UIButtonType 的Apple文档

旁注

我只想把这个作为旁注。此外,请阅读Apple编码惯例文档,因为我注意到您使用大写字母来启动变量名(即PlayButton)。变量名称应以小写字母开头(即playButton),类和枚举名称应以大写字母开头(如UIViewController)。坚持惯例总是很好的,因为这会使代码更具可读性和可维护性,所以如果其他开发人员来修改你的代码,他们甚至你自己都很容易阅读。

相关内容

最新更新