首页 > 解决方案 > 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
}

标签: swiftbuttonswift4programmatically

解决方案


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

@objc func handleLogOutButton() {

}

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


推荐阅读