potato
potato

Reputation: 4589

button placed on top of UIVisualEffectView not responding

I'm trying to add a button to UIVisualEffectView. However, the button that I add is not responding to touch events and I don't understand why. This is the code.

override func viewDidLoad() {
        super.viewDidLoad()
        let image = UIImage(named: "face2")
        let imageView = UIImageView(image: image)
        imageView.frame = CGRectMake(0, 0, 200, 200)
        let button = UIButton(frame: CGRectMake(50, 50, 100, 100))
        button.setTitle("huhuhu", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: .Normal)
        button.userInteractionEnabled = true

        let effect = UIBlurEffect(style: .Light)
        let blurView = UIVisualEffectView(effect: effect)
        blurView.frame = view.bounds

        view.addSubview(imageView)
        view.addSubview(blurView)
        view.addSubview(button)
    }

Upvotes: 1

Views: 878

Answers (1)

Sverrisson
Sverrisson

Reputation: 18167

You need to add the target action (button.addTarget), i.e. what is the button supposed to do when pressed, see your code modified below:

    class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let image = UIImage(named: "face2")
        let imageView = UIImageView(image: image)
        imageView.frame = CGRectMake(0, 0, 200, 200)
        let button = UIButton(frame: CGRectMake(50, 50, 100, 100))
        button.setTitle("huhuhu", forState: UIControlState.Normal)
        button.addTarget(self, action: "sayHi:", forControlEvents: .TouchUpInside)
        button.setTitleColor(UIColor.blackColor(), forState: .Normal)
        button.userInteractionEnabled = true

        let effect = UIBlurEffect(style: .Light)
        let blurView = UIVisualEffectView(effect: effect)
        blurView.frame = view.bounds

        view.addSubview(imageView)
        view.addSubview(blurView)
        view.addSubview(button)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func sayHi(sender:UIButton) {
        let randomIntH = arc4random_uniform(UInt32(view.bounds.size.width)-40)
        let randomIntV = arc4random_uniform(UInt32(view.bounds.size.height)-15)
        let frame = CGRectMake(CGFloat(randomIntH), CGFloat(randomIntV), 10, 10)
        let label = UILabel(frame: frame)
        label.text = "Hallo"
        label.sizeToFit()
        view.addSubview(label)
    }
}

Upvotes: 2

Related Questions