具有自定义UIView(包括按钮)的UIViewController无法识别水龙头

问题描述 投票:1回答:1

当尝试以编程方式将包含UIButton的自定义UIView(BaseHeader.swift)加载到UIViewController(ViewController.swift)时,按钮上的点击被识别为[[not。如果我在自定义UIView中提取代码并将其直接粘贴到UIViewController中,则所有水龙头都将被识别并按预期工作。我想念什么?起初,我认为在实例化后不为UIView定义帧大小是一个问题。我以为按钮可能没有按预期显示的“点击框”。给了视图一个框架后,我仍然没有运气,在谷歌搜索了一段时间后尝试了其他各种方法。

The view loads but button taps are not recognized -- see image

ViewController.swift

import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Authentication" } override func loadView() { super.loadView() let header = BaseHeader() header.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(header) NSLayoutConstraint.activate([ header.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), header.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), header.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: -10), ]) } }

BaseHeader.swift

import UIKit class BaseHeader: UIView { override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder: NSCoder) { super.init(coder: coder) } func setupView() { self.isUserInteractionEnabled = true let avenirFont = UIFont(name: "Avenir", size: 40) let lightAvenirTitle = avenirFont?.light let title = UILabel() title.text = "Title" title.font = lightAvenirTitle title.textColor = .black title.translatesAutoresizingMaskIntoConstraints = false self.addSubview(title) NSLayoutConstraint.activate([ title.topAnchor.constraint(equalTo: self.topAnchor, constant: 20), title.centerXAnchor.constraint(equalTo: self.centerXAnchor) ]) let profile = UIButton() let profileImage = UIImage(named: "person-icon") profile.setImage(profileImage, for: .normal) profile.setImage(UIImage(named: "think-icon"), for: .highlighted) profile.addTarget(self, action: #selector(profileTapped), for: .touchUpInside) profile.backgroundColor = .systemBlue profile.frame.size = CGSize(width: 30, height: 30) profile.isUserInteractionEnabled = true profile.translatesAutoresizingMaskIntoConstraints = false self.addSubview(profile) NSLayoutConstraint.activate([ profile.centerYAnchor.constraint(equalTo: title.centerYAnchor), profile.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20), ]) } @objc func profileTapped(sender: UIButton) { print("Tapped") } }
ios swift uiview uiviewcontroller uibutton
1个回答
0
投票
可能是您为自定义视图调用了错误的初始化程序,而没有调用setupView()函数。看起来在您正在调用的视图控制器中

let header = BaseHeader()

初始化视图,但这是此init:

override init(frame: CGRect) { super.init(frame: frame) setupView() }

即调用setupView()函数并设置水龙头。 
© www.soinside.com 2019 - 2024. All rights reserved.