首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么按钮上的addTarget函数不起作用?

为什么按钮上的addTarget函数不起作用?
EN

Stack Overflow用户
提问于 2020-02-08 22:00:04
回答 1查看 61关注 0票数 1

我正在实现一些函数,一旦按钮被点击就会被调用,但函数的主体不会被调用。下面是我的代码,它演示了我需要做的事情

代码语言:javascript
运行
复制
let editProfileFollowButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Edit Profile", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        button.layer.borderColor = UIColor.lightGray.cgColor
        button.layer.borderWidth = 1
        button.layer.cornerRadius = 3
        button.addTarget(self, action: #selector(handleEditProfileOrFollow), for: .touchUpInside)
        return button
    }()
    @objc func handleEditProfileOrFollow () {
        print("Execute edit profile or follow ")
    }

这是在我的init中发生的事情

代码语言:javascript
运行
复制
addSubview(editProfileFollowButton)
        editProfileFollowButton.setAnchor(top: postsLabel.bottomAnchor, left: postsLabel.leftAnchor, right: followingLabel.rightAnchor, bottom: nil, paddingBottom: 0, paddingLeft: 0, paddingRight: 0, paddingTop: 2, height: 34, width: 0)
    }

PS: setAnchor是我创建的一个函数,用于以编程方式设置视图的约束

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-08 22:17:40

从您所展示的代码中,最明显的就是您对let的使用

在使用闭包样式构建带有操作的变量时,我一直认为您应该使用lazy var实例化。这是因为(我相信) self在编译时是未知的。

代码语言:javascript
运行
复制
lazy var editProfileFollowButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Edit Profile", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        button.layer.borderColor = UIColor.lightGray.cgColor
        button.layer.borderWidth = 1
        button.layer.cornerRadius = 3
        button.addTarget(self, action: #selector(handleEditProfileOrFollow), for: .touchUpInside)
        return button
    }()
    @objc func handleEditProfileOrFollow () {
        print("Execute edit profile or follow ")
    }

lazy var的使用是一个在第一次使用时才计算其初始值的属性。(Source)

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60127494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档