Swift 4 上的编程按钮

Buttons Programmatically on Swift 4

一个简单的问题,我正在尝试创建一个名为 setupHeader() 的函数,在调用该函数时,会设置页眉的所有视图和按钮。问题出在“注销”按钮上,出于某种原因我无法正确处理。

第一个错误是按钮的 addTarget 无法识别 "self"。有什么建议吗?

第二个是#selector 只能与@objc func 一起使用,并且该函数不能在主setupHeader 函数中。我应该把它放在哪里?这是我的代码片段:

import Foundation
import UIKit

func setupHeader(vc: UIViewController) {

let headerFiller: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = supaGray
    return view
}()

let header: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = supaGray
    return view
}()

let logOutButton: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("Log Out", for: .normal)
    button.setTitleColor(.blue, for: .normal)
    button.titleLabel?.adjustsFontSizeToFitWidth = true
    button.titleLabel?.textAlignment = .left
    button.addTarget(self, action: #selector(handleLogOutButton), for: .touchUpInside)
    return button
}()

func handleLogOutButton() {

}

vc.view.addSubview(header)
header.topAnchor.constraint(equalTo: vc.view.safeAreaLayoutGuide.topAnchor).isActive = true
header.leftAnchor.constraint(equalTo: vc.view.leftAnchor).isActive = true
header.rightAnchor.constraint(equalTo: vc.view.rightAnchor).isActive = true
header.heightAnchor.constraint(equalToConstant: 40).isActive = true

header.addSubview(logOutButton)
logOutButton.centerYAnchor.constraint(equalTo: header.centerYAnchor, constant: -5).isActive = true
logOutButton.leftAnchor.constraint(equalTo: header.leftAnchor, constant: 7).isActive = true
logOutButton.widthAnchor.constraint(equalTo: header.widthAnchor, multiplier: 0.17).isActive = true
logOutButton.heightAnchor.constraint(equalToConstant: 40).isActive = true

vc.view.addSubview(headerFiller)
headerFiller.topAnchor.constraint(equalTo: vc.view.topAnchor).isActive = true
headerFiller.leftAnchor.constraint(equalTo: vc.view.leftAnchor).isActive = true
headerFiller.rightAnchor.constraint(equalTo: vc.view.rightAnchor).isActive = true
headerFiller.bottomAnchor.constraint(equalTo: header.topAnchor).isActive = true
}

您似乎正在将视图控制器传递到您的函数中,因此使用 self 无效。尝试使用 'vc'

以这种方式声明您的按钮按下回调。

@objc func handleLogOutButton() {

}

对于自我错误,请使用 vc 作为您在函数中传递的参数。

非常简单:

如下所示修改您的代码:

lazy var logOutButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Log Out", for: .normal)
button.setTitleColor(.blue, for: .normal)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.textAlignment = .left
button.addTarget(self, action: #selector(handleLogOutButton), for: .touchUpInside)
return button

}()

@objc func handleLogOutButton() {
// Do your things here
}