如何向自定义键盘 iOS 8 添加按钮图标?

问题描述 投票:0回答:4

我正在为 ios 8 创建自定义键盘。创建像这样的键盘按钮

    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];

我的问题是图像没有设置为按钮。我该如何解决这个问题?

我是否需要任何特殊步骤才能将图像添加到 Xcode 以用于自定义键盘?

ios ios8 ios-app-extension custom-keyboard
4个回答
6
投票

您可能没有将图像添加到键盘目标中。

检查您的键盘目标 > 构建阶段 > 复制捆绑资源以确保图像存在。如果没有,请将其拖到那里。

请注意,我说的是键盘目标,而不是主机应用程序。这可能就是这里的混乱。


3
投票

您可以像下面的步骤一样在自定义键盘上添加图像。

1.在您的 xcode 项目中添加图像

2.在键盘捆绑资源中添加图像。检查下面的图片

enter image description here

3.在按钮上设置带有背景的图像。检查下面的图片

enter image description here


1
投票

在自定义键盘文件夹中添加新的“资产目录”(“KeyboardViewController.swift”文件所在的位置。

然后将您的图像添加到“Assets Catalog”文件夹中并使用以下代码。

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)

0
投票

非常感谢。为我工作!!!

© www.soinside.com 2019 - 2024. All rights reserved.