3

i have this code for the UIView subclass.

import UIKit

class DrawingSquareView: UIView {


    override func drawRect(rect: CGRect)
      {
        var apertureRect : CGRect = CGRectMake(80, 200, 160 , 158)
        var context : CGContextRef = UIGraphicsGetCurrentContext()

            /* draw the transparent rect */
        CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 0.0)
        CGContextSetBlendMode(context, kCGBlendModeCopy)
        CGContextFillRect(context, apertureRect)

    //        /* draw a white border */
        CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0)
        CGContextStrokeRect(context, apertureRect)
     }
    override func awakeFromNib()
    {
    var cropButtons : UIButton = UIButton(frame: CGRectMake(70, 150, 160 , 158))
    cropButtons.setTitle("Crop Image", forState: UIControlState.Normal)
    cropButtons.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
    self.addSubview(cropButtons)

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

     override func hitTest(point: CGPoint, withEvent event: UIEvent!) -> UIView!
     {
        var view : UIView = self.superview
        return view.viewWithTag(99)

    }
   }

and also this code for calling the UIView subclass in the UIViewController class

@IBAction func CropButtonClicked(sender: UIButton)
    {
        var DrawingSquareObject : DrawingSquareView = DrawingSquareView(frame:self.view.frame)
        self.view.addSubview(DrawingSquareObject)
   }

but when I click in the button in the superview , it does showing the rectangle that I created in the UIView subclass by using the draRect: , But it showing the UIButton that I created in the awakefromNib(). I tried adding the subview in the init(frame:), init(coder:), addsubview(view:) functions, none of them show the UIButton. Also I want to know how can I remove this DrawingSquareView from the superview.

Please help me , Thank you in advance.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Alvin Varghese
  • 842
  • 10
  • 33

1 Answers1

1

I think your first problem is that the view is not initialized during init, so do not attempt to add subviews then.

To remove DrawingSquareView from its superview, try this:

    for view in self.view.subviews {
        if view is DrawingSquareView {
            view.removeFromSuperview()
        }
    }
hcanfly
  • 172
  • 4