gpt4 book ai didi

swift - “NSInvalidArgumentException”关闭

转载 作者:行者123 更新时间:2023-11-30 10:35:02 33 4
gpt4 key购买 nike

我正在练习创建一个主要不使用 Storyboard的 UI,当我开始调试时,我的应用程序崩溃了,并给我带来了这个错误。

我尝试从 info.plist 和目标中删除“main”,但不起作用

2019-10-03 12:43:13.699871+0200 provolone[3580:115566] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't add self as subview'

这是 myViewController,Xcode 11.1 GM 种子 (11A1027)

import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let view = UILabel()

view.frame = CGRect(x: 0, y: 0, width: 252, height: 60)
view.backgroundColor = .white
self.view = view

view.textColor = UIColor(red: 0.33, green: 0.36, blue: 0.49, alpha: 1)
view.font = UIFont(name: "OpenSans-Bold", size: 26)
view.numberOfLines = 0
view.lineBreakMode = .byWordWrapping
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 0

// Line height: 30 pt

view.textAlignment = .center
view.attributedText = NSMutableAttributedString(string: "Connect with people\nyou love.", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])

let parent = self.view!
parent.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.heightAnchor.constraint(equalToConstant: 60).isActive = true
view.centerYAnchor.constraint(equalTo: parent.centerYAnchor, constant: 137).isActive = true
}
}

最佳答案

问题似乎出在这一行:

self.view = view

这样,您就可以将刚刚创建的标签指定为您的 View 。如果您想将标签添加到 View 中,只需按如下所示添加即可:

self.view.addSubview(view)

为了便于阅读,我还建议您重命名标签。并且不需要创建父 View 来添加标签,除非您有在此代码片段中不清楚的原因。进行这些更改后,您的代码将如下所示:

import UIKit

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

let view = UILabel()

view.frame = CGRect(x: 0, y: 0, width: 252, height: 60)
view.backgroundColor = .white

view.textColor = UIColor(red: 0.33, green: 0.36, blue: 0.49, alpha: 1)
view.font = UIFont(name: "OpenSans-Bold", size: 26)
view.numberOfLines = 0
view.lineBreakMode = .byWordWrapping
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 0

// Line height: 30 pt

view.textAlignment = .center
view.attributedText = NSMutableAttributedString(string: "Connect with people\nyou love.", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])

self.view.addSubview(view)

view.translatesAutoresizingMaskIntoConstraints = false
view.heightAnchor.constraint(equalToConstant: 60).isActive = true
view.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 137).isActive = true
}
}

关于swift - “NSInvalidArgumentException”关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58217552/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com