Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Set label to be on top of other view items

Tags:

ios

swift

I'm creating a basic sketching app using swift 1.2 and Xcode 6.4. The feature I'm working on is adding text to the image for future manipulation.

So far I have the text the user enters adding to the drawing via label, but it is being placed (I assume) behind the UIImage that is to be drawn upon. This is preventing the associated tap gesture from being recognised. The label is also obscured when drawn over.

How do I place the label on top of everything else to prevent it being drawn over? The end goal is to allow the user to move the label.

If I was using my usual web stack I'd set the z-index of the element to a high value via CSS.

Edit: Using view.bringSubviewToFront(label) prevents the text from being drawn over, but does not allow the tap gesture to be picked up.

Heres my code:

    func printText(){
        println(textString)

        var label = UILabel(frame: CGRectMake(5, 100, 200, 50 ))
        label.textAlignment = NSTextAlignment.Center
        label.text = textString;

        let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap"))
        label.addGestureRecognizer(tap)

        self.view.addSubview(label);
    }

    func handleTap() {
        print("tap working")
    }

Any help much appreciated.

like image 480
tonyedwardspz Avatar asked Sep 09 '15 11:09

tonyedwardspz


3 Answers

If you want z-index use:

label.layer.zPosition = 1;

Also you could play with bringToFront method on the parent view:

self.view.bringSubviewToFront(label);

You can check that function here : https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/

Also, you should add the following:

label.userInteractionEnabled = true

to enable touches.

like image 143
Miknash Avatar answered Oct 13 '22 23:10

Miknash


Try using those in the parent view:

view.bringSubviewToFront(label)
view.sendSubviewToBack(imageView)

It all depends on what you can, or want to do.

like image 36
Rafal Avatar answered Oct 13 '22 22:10

Rafal


You can call label to front by

self.view.bringSubviewToFront(label)

or

You can send image view to the back by

self.view.sendSubviewToBack(imageView)
like image 3
simardeep singh Avatar answered Oct 14 '22 00:10

simardeep singh