Change position of attributed title in button

痞子三分冷 提交于 2019-12-11 06:18:43

问题


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.

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


回答1:


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

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

now u need to set alignment for example,

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

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

and now your button looks something like below,

hope this helps u :)




回答2:


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 : -

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



来源:https://stackoverflow.com/questions/38852820/change-position-of-attributed-title-in-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!