我为按钮创建了一个类和函数:
class FloatingActionButton: UIButtonX {
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
UIView.animate(withDuration: 0.3, animations: {
if self.mapTypeButton.transform == .identity {
self.mapTypeButton.transform = CGAffineTransform(rotationAngle: 45 * (.pi / 180)) .
} else {
self.mapTypeButton.transform = .identity
return super.beginTracking(touch, with: event)}
现在我在另一个类 ViewController 中,我想调用我的函数(请参阅更新了解我为什么要调用我的函数)
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
self.closeMapType()
FloatingActionButton().beginTracking(touch: UITouch, with: UIEvent?)
return true
}
但有人告诉我 beginTracking 不是可以调用的函数类型。
更新:
我在 Storyboard 上设置了按钮并将其连接到指针。现在,按钮的位置类似于 this。 (照片 1),(很抱歉我没有足够的声誉点数来发布照片)。当我在模拟器中点击它时,它会变为 this (照片 2),当我再次点击它时,它会变回默认状态。所有这些功能都在 FloatingActionButton 类
中设置。
可以将 UIView.animate(etc.)
放在 func searchBarShouldBeginEditing
中,但我想知道我是否可以调用 UIView.animate (etc.)
以减少冗余。
我现在要做的是当我点击搜索栏时,如果按钮处于旋转状态(照片 2),它将旋转回原始状态(照片 1)。我创建了:
@IBOutlet weak var mapTypeButton: FloatingActionButton!
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
UIView.animate(withDuration: 0.3, animations: {
if self.mapTypeButton.transform == .identity {
return
} else {
self.mapTypeButton.transform = .identity
})
return true
}
它完全符合我的要求。我没有调用函数,而是将函数操作添加到新函数中。感谢大家的帮助
最佳答案
听起来你并不真正了解面向对象编程。
按钮对象不应该存在于真空中。按钮是一个用户界面元素,它属于屏幕上的某个地方。
这段代码:
FloatingActionButton().beginTracking(touch: UITouch, with: UIEvent?)
创建一个全新的 FloatingActionButton
,告诉它开始跟踪触摸,然后忘记它。它从不与任何事物有任何联系。没有人拥有它,所以当 searchBarShouldBeginEditing 函数返回时,按钮对象被释放。
这个按钮是否应该显示在屏幕上的某个地方,并跟踪触摸?如果是这样,您需要决定哪个 View 应该承载它,并将其添加到该 View 。您还需要设置 AutoLayout 约束,以便将其放置在其父 View 中。
一般来说,在 Storyboard 中创建用户界面并以这种方式将它们放置在 View 层次结构中会更容易(而且通常更好)。不过,为了帮助您解决这个问题,您需要解释此按钮如何适合您的用户界面。
编辑:
根据您的更新,您想更改 Storyboard中按钮的设置。 (请注意,您尝试对按钮进行的调用很可能是错误的,但是我将向您详细介绍如何获取指向按钮或其他 View 的指针(IBOutlet
),以便你可以配置它。)
您这样做的方法是在主编辑器窗口中设置 Storyboard,然后在“辅助编辑器”中打开包含该按钮的 View Controller 的源文件。我建议为此选择“底部的助理编辑器”选项。
现在您按住 control 键,按下您的按钮,然后按住 control 从按钮拖动到 View Controller 类的内部,在顶部靠近其他变量的地方。 Xcode 将为您的按钮创建一个 IBOutlet。在出现的对话框中,将“发件人”的类型更改为您的按钮类型(“FloatingActionButton”)。如果 Xcode 不允许您这样做,请查看是否可以选择“UIButton”。给它起一个像“myFloatingButton”这样的名字。
现在更改您的代码
FloatingActionButton().beginTracking(touch: UITouch, with: UIEvent?)
到
myFloatingButton.beginTracking(touch: UITouch, with: UIEvent?)
您所做的是在您的 View Controller 中创建一个实例变量 myFloatingButton
。当操作系统加载 View Controller 的 View 时,它将在该实例变量中保存一个指向 float 按钮的指针。一旦你的 View 加载(一旦你的 viewDidLoad()
方法被调用)你可以假设你的变量 myFloatingButton
指向你的按钮,然后可以调用你的方法来配置它.
编辑#2:
正如 Hasan 在他的回答中指出的那样,您在按钮上调用 beginTracking(_:with:)
是没有意义的。这是 UIButton
(实际上是按钮的祖先类 UIControl
)的一个方法,当用户触摸按钮时系统会在内部调用该方法。
您必须解释您想要做什么,以便我们能够帮助您完成。
关于ios - 在函数swift中从另一个类调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45765373/