使用 swift3 在​​ ios 中单击时更改按钮上的文本

changing the text on the button on clicking in ios using swift3

场景:

我有 VC,其中我水平放置了 4 UIButton4 UIImageView,每个按钮都有每次按下它们时,它们各自的视图控制器都会显示相应的 VC

问题:

图片:

  1. 您可以子类化 UIButton 来创建您自己的按钮。最终,一个按钮继承自 UIView,因此,您可以简单地子类化并添加您想要添加到按钮的任何样式。子类化 UIButton 将在设计方面给予您绝对的自由。也可以使用API函数设置按钮的image/text,如下图

    button.setImage(UIImage(named: "<image placeholder>") for: .normal)

    请注意,.normal 是按钮的状态,对 normal 状态的任何更改都会应用到按钮的所有其他状态。如果您想更改特定状态,您应该提及。

  2. 我们将选择器附加到按钮的触摸事件。选择器在事件(如 touchupinside aka click)发生时被调用。在此选择器中,您可以为按钮的新字体编写代码。您可以将字体设置如下

    myButton.titleLabel!.font = UIFont(name: YourfontName, size: 20)

当然你可以用一个按钮,因为我们可以给一个按钮设置图片和文字。

button.setImage(UIImage(named: "imageName") for: .normal)
button.setTitle("the title string", for: .normal)

和按钮文字字体:

button.titleLabel?.font = UIFont(name: "font string you want", size: 18)

突出显示的状态颜色:

button.setTitleColor(UIColor.red, for: .highlighted)

与Objective-C您可以交换按钮中的图像和文本位置:

_titleViewBtn.size=CGSizeMake(100, 20);

CGFloat imgX=_titleViewBtn.imageView.frame.origin.x;
CGFloat titleX=_titleViewBtn.titleLabel.frame.origin.x;
if (imgX<titleX) {
    CGRect titleFrame=_titleViewBtn.titleLabel.frame;
    titleFrame.origin.x=imgX;
    _titleViewBtn.titleLabel.frame=titleFrame;

    CGRect imgFrame=_titleViewBtn.imageView.frame;
    imgFrame.origin.x=CGRectGetMaxX(_titleViewBtn.titleLabel.frame);
    _titleViewBtn.imageView.frame=imgFrame;

}

您可以在 UIButton 中使用文本和图像,如下所示

button.setImage(UIImage(named: "imageName") for: .normal)
button.setTitle("Title", for: .normal)

使用 UIButton 的 contentHorizo​​ntalAlignment 将按钮标题设置在图像的左侧或右侧。

使用UIButton的imageEdgeInsets和contentEdgeInsets设置margin

使用 UIButton 的 IBAction 改变点击按钮的图像、标题和字体

使用UIButton的.highlighted状态设置UIButton高亮状态下的图片和标题

你可以设置 button.setImage(image: UIImage(named: "abc"), for: .normal) button.setTitle(image: "abc", for: .normal)

您更改状态操作按钮“.normal”是其他状态。

所以这里的伙计们是最好的解决方案:

Q1) 问题是我必须更改文本颜色和图像颜色 我用过点击按钮。 一)一个。将按钮拖放到 VC b.在 ATTRIBUTES INSPECTOR 默认情况下状态是 default 选择 你想要的颜色我选择灰色然后点击旁边的箭头 默认并选择 SELECTED 状态并选择颜色和图像 在图像中放置 image.png。 C。转到SIZE INSPECTOR并调整图像和文本的大小 按钮 。 d.转到您尊敬的 swift 文件并创建每个按钮 iboutlet 和 ibaction ,在每个按钮的动作中使用以下行:

   button1.isselected = true
   button2.isselected = false

对我有用。

Q2)是否可以使用带有图像和文本的单个按钮?

A) 是的步骤在上面

Q3)如何改变按钮被点击时的字体。 A) 仍在工作