当内部按钮触摸时,如何从 Superview 中删除以编程方式创建的子视图?
Posted
技术标签:
【中文标题】当内部按钮触摸时,如何从 Superview 中删除以编程方式创建的子视图?【英文标题】:How to remove a programmatically created subview from Superview when button touch up inside? 【发布时间】:2015-09-04 14:34:05 【问题描述】:我有一个系统,当用户点击另一个按钮(命名为按钮)时,生成新视图(在图片上用蓝色矩形标记)和按钮(用绿色圆圈标记)作为 Superview 的子视图(用红色矩形标记) .他们都以编程方式创建。我可以根据带有操作消息的 button.tag 删除“减号按钮”。问题是如何删除减号按钮旁边的子视图?它也有与减号按钮相同的标签。
下面是我的mainButton IBAction ;
@IBAction func mainButton(sender: UIButton)
drawThem()
minusButtonY = counter == 0 ? (minusButtonY + 101) :(minusButtonY + 68)
borderY = counter == 0 ? (borderY + 86) : (borderY + 68)
counter++
drawFooter()
completePaymentView.contentSize = counter > 7 ? (CGSizeMake(500.0, ( borderY ))) : (CGSizeMake(500.0, ( 490.0 )))
以及我生成新视图和按钮的方法;
func drawThem()
//creating minus button
let image = UIImage(named: "minus.png") as UIImage?
let button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
var mX : CGFloat = 2.0
var mY : CGFloat = minusButtonY >= 36.0 ? minusButtonY : 36.0
button.frame = CGRectMake(mX, mY, 22, 22)
button.setImage(image, forState: .Normal)
button.tag = Int(counter)
button.addTarget(self, action:"btnTouched:", forControlEvents:.TouchUpInside)
completePaymentView.addSubview(button)
//drawing payment section border
var x : CGFloat = 43.0
var y : CGFloat = borderY >= 20.0 ? borderY : 20.0
let size = CGSize(width: 485 , height: 55)
let borderView = UIView(frame: CGRect(origin: CGPoint(x: x , y: y), size: size))
borderView.layer.borderColor = UIColor(red: 0.83, green: 0.85, blue: 0.88, alpha: 1.0).CGColor
borderView.layer.borderWidth = 2.0
borderView.layer.cornerRadius = 5.0
borderView.tag = counter
completePaymentView.addSubview(borderView)
//drawing UIImage and Labels into border
let imageName = "circle.png"
let thumb = UIImage(named: imageName)
let imageView = UIImageView(image: thumb!)
imageView.frame = CGRect(x: 14, y: 8, width: 55, height: 35)
borderView.addSubview(imageView)
let label1 = UILabel(frame: CGRect(x: 85, y: 20, width: 100, height: 18)) as UILabel
label1.text = "Some Text"
label1.textColor = UIColor(red: 0.49, green: 0.54, blue: 0.6, alpha: 1.0)
label1.font = label1.font.fontWithSize(14.0)
label1.textAlignment = .Left
borderView .addSubview(label1)
let label2 = UILabel(frame: CGRect(x: 370, y: 20, width: 100, height: 18)) as UILabel
label2.text = "Some Text"
label2.textColor = UIColor(red: 0.49, green: 0.54, blue: 0.6, alpha: 1.0)
label2.font = label2.font.fontWithSize(14.0)
label2.textAlignment = .Right
borderView .addSubview(label2)
和下面的目标操作;
func btnTouched(button : UIButton)
button.removeFromSuperview()
【问题讨论】:
通过tag
找到它 - 互联网上有很多例子。
【参考方案1】:
在 btnTouched 方法中添加以下内容。实际上我正在搜索所有子视图以找到标签。
for view in self.view.subviews as! [UIView]
if view.tag == button.tag
view.removeFromSuperview()
【讨论】:
行了!我刚刚根据我的代码将 self.view.subviews 更改为 self.completePaymentView.subviews 并且得到了!谢谢。以上是关于当内部按钮触摸时,如何从 Superview 中删除以编程方式创建的子视图?的主要内容,如果未能解决你的问题,请参考以下文章
防止从 UIImageView 到 superview 的触摸传输