当我通过#selector(didTapRegister)
运行此代码时,我得到didTapRegister
不在范围内。我在一个更大的应用程序中使用它,在一个页面上它可以工作,而在另一个页面上它不能工作,它在其他任何地方都不能工作。我一直想找出原因。有人能帮忙解决吗?似乎是一个Objective-C问题可能是因为我有同样的问题,试图使iboutlet,我试过寻找答案,我只是没有足够的知识来理解为什么它不工作,我试过将代码移动到不同的范围,仍然没有什么。对于IBOutlet它说IBOutlet属性不能有非对象类型UIButton。类型
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let Button = UIButton.init(type: .custom)
Button.setTitle("Chat", for: .normal)
Button.layer.backgroundColor = CGColor.init(gray: 0.0, alpha: 0.0)
Button.setTitleColor(.white, for: .normal)
Button.setTitleColor(.red, for: .highlighted)
Button.layer.borderWidth = 1
Button.layer.cornerRadius = 5
Button.layer.borderColor = UIColor.white.cgColor
Button.isHighlighted = false
Button.showsTouchWhenHighlighted = true
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: Button)
Button.addTarget(self, action: #selector(didTapRegister), for: .touchUpInside)
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Do any additional setup after loading the view.
}
}
}
不妨试试他说的话,但是
就用SwiftUI吧,好多了
@objc所有这些都很好但是在SwiftUI中你可以右键点击并添加按钮
代码中有两个错误
- 你必须为按钮动作创建
@objc
函数 - 在你的代码中将
viewWillAppear
方法移出viewDidLoad
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton.init(type: .custom)
button.setTitle("Chat", for: .normal)
button.setTitleColor(.white, for: .normal)
button.setTitleColor(.red, for: .highlighted)
button.layer.borderWidth = 1
button.layer.cornerRadius = 5
button.layer.borderColor = UIColor.white.cgColor
button.isHighlighted = false
button.showsTouchWhenHighlighted = true
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
button.addTarget(self, action: #selector(didTapRegister), for: .touchUpInside)
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
}
@objc func didTapRegister(_ sender: UIButton) {
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Do any additional setup after loading the view.
}
}
注意:按钮名称以小写字母开头。