tphduy
tphduy

Reputation: 126

Change position of attributed title in button

button

As you see, I want the title is under the image and the both of them center horizontally. Be careful, they are components of a button. I tried changing inset value on interface builder but it didn't work with others screen (I use auto layout), it messed up.

enter image description here

Can I do it by using IB or have to "hard code"

Upvotes: 1

Views: 833

Answers (2)

Shankar BS
Shankar BS

Reputation: 8402

in interface builder it is easy, just add a button change it to type custom like below image and also title as settings

enter image description here

and set the image for your button, i set it as settingsButton.png.

enter image description here

now u need to set alignment for example,

enter image description here

now u can set the insects for image and title, to set insect for image u select the edge for image like below image, and adjust the insect

enter image description here

and for title, now select edge for title and adjust the insect like below image,

enter image description here

and now your button looks something like below,

enter image description here

hope this helps u :)

Upvotes: 1

Dravidian
Dravidian

Reputation: 9945

Try adding a CAShapeLayer to the Button :-

1.) Define a UIBezierPath with the rect : frame same as that of button

2.) Define a CAShapeLayer with path to that of a bezierPath

3.) Add text "B" to the centre of the button by adding a CATextLayer : https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CATextLayer_class/

4.) Add that shapeLayer and textLayer as subLayer to the layer of button, give those layer a respective zPosition in this case -1

5.) Set opacity(alpha) for the first layer i.e Button.

Here is what its code might look like : -

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var btn: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    setupButton()

}

func setupButton(){

    print(btn.bounds)
    print(btn.frame)

    let bezPath : UIBezierPath = UIBezierPath(rect: btn.bounds)
    let lyr : CAShapeLayer = CAShapeLayer()
    let txtLyr : CATextLayer = CATextLayer()
    lyr.path = bezPath.CGPath
    lyr.fillColor = UIColor.blueColor().CGColor
    lyr.zPosition = -1
    lyr.opacity = 0.5
    txtLyr.string = "B"
    //        txtLyr.font = 
    txtLyr.fontSize = 38.0
    txtLyr.zPosition = -1
    txtLyr.frame = btn.bounds
    print(txtLyr.frame)
    txtLyr.alignmentMode = kCAAlignmentCenter
    btn.layer.addSublayer(lyr)
    btn.layer.addSublayer(txtLyr)
}


@IBAction func btnAction(sender: UIButton) {

     print("Button is pressed!")

  }
}

With this being the Output : - Simulator Screen

PS: 1.) In your case only CATextLayer would be needed...

2.) That red circle thing that you see in the button is an image.

I hope this helps

Upvotes: 0

Related Questions