ios - Xcode 我的应用程序无法在 iPad 模拟器中运行,但可以在 iPhone 模拟器中运行
问题描述
此代码当前以“警告可能导致癫痫发作”的消息开头,当您按下作为按钮的消息时,屏幕将闪烁随机颜色。在 mainstory 板中,我将 didTapAdd 操作拖到我制作的按钮上。它适用于所有 iPhone 模拟器,但是当我在 iPad 上按下消息时,什么也没有发生。怎么会这样 ?
import UIKit
class ViewController: UIViewController {
let colors: [UIColor] = [
.systemYellow,
.systemGreen,
.systemPurple,
.systemPink,
.systemRed,
.systemBlue,
.systemOrange,
.magenta, .darkGray, .gray, .lightGray, .brown, .cyan
]
var label: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
let label = UILabel()
view.addSubview(label)
label.text = "Warning. May cause a seizure."
label.textColor = UIColor.white
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 200),
label.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
self.label = label /// assign self.label, so we can access it later
}
@IBAction func didTapButton() {
if let myLabel = label {
myLabel.removeFromSuperview()
self.label = nil /// set to nil, so we won't try to remove it again
}
let color1 = self.colors.randomElement()
let color2 = self.colors.randomElement()
self.view.layer.removeAllAnimations()
self.view.backgroundColor = color1 /// set to color1
UIView.animate(withDuration: 1/25, delay: 0, options: [.repeat, .autoreverse, .allowUserInteraction]) {
self.view.backgroundColor = .black
self.view.backgroundColor = color2// now animate to color2, reverse, then repeat
}
}
}
解决方案
确保添加约束——它们很复杂,但这里有一个很好的入门指南。但是,对于您的情况,简单的“对齐”约束应该可以正常工作。
- 在情节提要中选择您的按钮
- 检查两者
Horizontally in Container
和Vertically in Container
- 在键盘上按Return/Enter
- 查看结果: