【发布时间】:2015-08-16 08:22:31
【问题描述】:
我有一个类ManageCell,它存储框架、设置标签文本等...这是ViewController 中的UIView CellView 的子视图。
管理单元:
import Foundation
import UIKit
class ManageCell {
var name: UILabel
var viewBelowButton: UIView
var deleteButton: UIButton
init (name: String) {
self.name = UILabel(frame: CGRectMake(10,15,250,40)
self.name.text = name
self.name.sizeToFit()
self.viewBelowButton = UIButton(frame: CGRectMake(UIScreen.mainScreen.bounds.width, 0, 70, 70)
//set outside the visible area so that it can be animated in.
self.viewBelowButton.backgroundColor = UIColor.redColor()
self.deleteButton = UIButton(frame: CGRectMake(0,0,70,70))
self.deleteButton.addTarget(ViewController.self, action: "deleteButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
self.deleteButton.setTitle("delete", forState: .Normal)
}
}
视图控制器:
var cellView: [UIView] = []
var manageCells: [ManageCell] = []
...
//fill the manageCells array
func setSubViews () {
for (index, cell) in manageCells.enumerate() {
cellView.append(UIView(frame: CGRectMake(0, originY, view.bounds.width, 70)
cellView[index].addSubview(cell.name)
cellView[index].addSubview(cell.viewBelowButton)
cell.viewBelowButton.addSubview(cell.deleteButton)
}
}
func editing () {
var frame = CGRectMake(view.bound.width - 70, 0, 0, 70)
for cell in cells {
UIView.animateWithDuration(0.2, animations: {
cell.viewBelowButton.frame = frame
}
}
}
func deleteButtonPressed(sender: UIButton) {
print("button pressed")
}
在
cellView[index]、viewBelowButton和deleteButton上都启用了用户交互。
我面临的问题是deleteButton 不响应触摸。 deleteButtonPressed: 函数未被调用。
代码:https://github.com/an23lm/swift-stuff
我不确定这是否是好的做法,欢迎提出任何建议。
【问题讨论】:
-
听起来按钮在其超级视图之一的框架之外。尝试为所有涉及的视图将
clipsToBounds设置为true。如果我是正确的,您将无法再看到按钮(或至少部分按钮)。 -
在 ViewController 类中添加按钮时,为什么不做 addTarget 呢?这样,您将在同一个类中拥有选择器。还要按照 Aaron 的正确建议检查框架。
-
@GurtejSingh 好点。这是另一个问题,尽管按钮点击甚至没有注册,否则 OP 会崩溃。
-
@AaronBrager 同意!但我怀疑问题出在 ViewController.self 上。我认为这不是一个例子。
-
@GurtejSingh,我将
addTarget移动到ViewController,现在它是cell.deleteButton.addTarget(self, action: "self.deleteButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside),仍然没有。是的,你对坠机的看法是对的,奇怪的是我没有坠机。 @AaronBrager,我确实将viewBelowButton移动到屏幕的框架中并删除了动画(以确保deleteButton被初始化为它下方的所有超级视图),并使用了clipToBounds,但没有任何变化。