4

I am creating custom keyboard for ios 8. Creating keyboard buttons like this

    UIButton *aBtn = [ UIButton buttonWithType:UIButtonTypeCustom ];

    [aBtn setFrame:CGRectMake(x, 30, btnWidth, btnHeight)];

    [aBtn setImage:[UIImage imageNamed:@"A"] forState:UIControlStateNormal];

    [aBtn setTitle:@"A" forState:UIControlStateNormal];
    [aBtn setTitleColor:[ UIColor blackColor] forState:UIControlStateNormal];
    [aBtn setTitleColor:[ UIColor whiteColor] forState:UIControlStateHighlighted];
    [aBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:aBtn];

My problem is that the image is not set to button. How can I solve this?

Do I need any special steps to be able to add images to Xcode for custom keyboards?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Anbu Raj
  • 831
  • 2
  • 8
  • 25

3 Answers3

6

You probably didn't add the image to your keyboard target.

Check your keyboard target > Build Phases > Copy bundle resources to make sure that the image is there. Drag it there if it isn't.

Note that I am talking about the keyboard target, not the host app. That could be the confusion here.

honcheng
  • 2,014
  • 13
  • 14
2

You can add image on custom keyboard like below steps.

1. Add images in your xcode project

2. Add images in keyboard bundle resources. check below image

enter image description here

3. Set image with background on button. check below image

enter image description here

Community
  • 1
  • 1
Hardik Mamtora
  • 1,642
  • 17
  • 23
1

Add a new "Assets Catalog" in your custom keyboard folder ( Where "KeyboardViewController.swift" file is located.

enter image description here

Then add your image in "Assets Catalog" folder and use the following code.

let button = UIButton(type: UIButton.ButtonType.system) as UIButton     
button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
if let image  = UIImage(named: "image_name") { // no need to use ".png format"
    button.setBackgroundImage(image, for: .normal)
}
button.backgroundColor = .red // to show button position
view.addSubview(button)
Patrick
  • 5,526
  • 14
  • 64
  • 101