LC 웃
LC 웃

Reputation: 18998

How to Display Image over Button? -Swift

I am creating a UIButton programmatically and set the title, image as the below code. The problem is whenever i click on the button the image gets highlighted but the title of the button does not. So, i want to create the animation effect of both or none. As well as should i give constraints or what so that image gets right of the text "SORT"?

enter image description here

Upvotes: 1

Views: 1965

Answers (2)

Suraj Sonawane
Suraj Sonawane

Reputation: 2494

Here is code for sample, you can try it. I have created one button programatically and assign image with the help of EdgeInsets property.

       let btnDemo : UIButton  = UIButton() 
        btnDemo.frame = CGRect(x: 5, y: 75, width: 65, height: 18)
        btnDemo.setImage(UIImage(named:"drop_arrow_sample"), forState: UIControlState.Normal)
        btnDemo.imageEdgeInsets = UIEdgeInsets(top: 6,left: 100,bottom: 6,right: 14)
        btnDemo.titleEdgeInsets = UIEdgeInsets(top: 0,left: -30,bottom: 0,right: 34)
        btnDemo.titleLabel?.font = UIFont(name: "Helvetica Neue", size: 13)
        btnDemo.layer.cornerRadius = 2.0
        btnDemo.titleLabel?.textColor = UIColor.whiteColor()
        btnDemo.backgroundColor = UIColor(red: 189/255, green: 176/255, blue: 0/255, alpha: 1)                      
        btnDemo.tag = index
        btnDemo.addTarget(self, action: "SortTable:", forControlEvents: UIControlEvents.TouchUpInside)

Upvotes: 0

LC 웃
LC 웃

Reputation: 18998

I nailed it. I changed the button type to System button and the color changed to blue. However i managed to change the Blue color to white by setting the tint color to white which apple uses by default to set the color to its controls(i guess). So the system button color to blue was due to the reason the tintcolor was assigned as blue

let btnSort   = UIButton.buttonWithType(UIButtonType.System) as UIButton
btnSort.frame =  CGRectMake(2, 74, 140, 26)
btnSort.tintColor = UIColor.whiteColor()
btnSort.setImage(UIImage(named:"drop_arrow"), forState: UIControlState.Normal)
btnSort.imageEdgeInsets = UIEdgeInsets(top: 6,left: 100,bottom: 6,right: 14)
btnSort.titleEdgeInsets = UIEdgeInsets(top: 0,left: -30,bottom: 0,right: 34)
btnSort.setTitle("SORT", forState: UIControlState.Normal)
btnSort.layer.borderWidth = 1.0
btnSort.layer.borderColor = UIColor.whiteColor().CGColor
btnSort.addTarget(self, action: Selector("showSortTbl"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btnSort)

Upvotes: 1

Related Questions