swift - 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
}
解决方案
以这种方式声明您的按钮按下回调。
@objc func handleLogOutButton() {
}
对于自我错误,请使用 vc 作为函数中的上述参数传递。
推荐阅读
- javascript - 如何使用jquery ajax更改排序箭头升序和降序
- javascript - 增量运算符在 Sequelize 中不起作用
- elsa-workflows - elsa-workflows 与 .net 框架集成
- node.js - 如何强制云函数不在调用之间保留变量?
- java - 在 Spring Security 中保护字符串查询的问题
- c# - Unity3D角色没有朝其面对的方向移动
- angular - 从模板中检索输入/输出参数
- linux - Hazelcast 4.2 独立作为 linux 服务
- sql - 从 NodeJS 执行插入查询时出现“如果对象已关闭,则此操作未被授权”错误
- flutter - Flutter中容器中的TextField中心