gpt4 book ai didi

swift - Apple iOS 教程 : Problems getting UIButton addTarget to Work

转载 作者:行者123 更新时间:2023-11-28 12:35:53 26 4
gpt4 key购买 nike

我正在学习 Apple 提供的“开始开发 iOS 应用程序”教程,但在 Implement a Custom Control 中遇到问题部分。我已经尝试了所有方法来让按钮打印一些东西到控制台,但无法让它工作。我位于教程“将按钮添加到 View ”部分的页面下方大约五分之一处。

其他一切正常。

我已经设置了 RatingControl.swift 文件如下:

import UIKit

class RatingControl: UIView {

// MARK: Initialisation
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

// Create a square button
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))

// Set the background colour of the button
button.backgroundColor = UIColor.darkGray

button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .touchDown)

// Add the button to the view
addSubview(button)
}

// MARK: Button Action
func ratingButtonTapped(_: UIButton) {
print("Button pressed")
}
}

有些地方与教程略有不同,但那是因为 Xcode 说事情已经改变了。在我的 Main.storyboard 文件中,我使用 RatingControl 类添加了一个 View 。按钮显示,但单击它时没有任何反应。

如有任何帮助,我们将不胜感激。如果需要任何额外信息,请告诉我。

最佳答案

这个故事中实际上有一个三 View 的层次结构:

  • 堆栈 View (原始问题中未提及)
    • 评级控件
      • 按钮

好吧,堆栈 View 是一个复杂的控件,它的工作涉及很多巫术及其排列 subview 的约束,正在将 RatingControl 的大小减小到零。因此,该按钮位于 RatingControl 的边界之外(通过为 RatingControl 提供背景颜色很容易证明——背景颜色不会出现)。 RatingControl 不会裁剪到其边界,因此按钮仍然可见 — 但是,在其父 View 之外,它不是可点击的

至于为什么堆栈 View 将 RatingControl 的大小减小为零:这是因为 RatingControl 没有 intrisicContentSize。我们需要这个的原因很复杂,并且与堆栈 View 如何操作其排列的 subview 并为它们提供约束有关。但本质上,它根据排列 View 的 intrinsicContentSize 做出很多决定。

在评论中你说:

In size inspector it has intrinsic size set to placeholder, width 240, height 44. Or is there something I need to do to stop the stack view making it zero sized?

这里要理解的关键是尺寸检查器中的设置只是一个占位符。它只是关闭 Storyboard,这样它就不会提示了。它实际上并没有在运行时为 View 提供任何固有大小。为此,您实际上必须覆盖 intrinsicContentSize property在您的代码中,作为返回实际大小的计算变量。

关于swift - Apple iOS 教程 : Problems getting UIButton addTarget to Work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40944037/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com