Swift 中具有多个可访问标签和图像的按钮

Button with multiple accessible labels and images in Swift

我需要创建自定义按钮 class,重复使用它 4 次,我还需要覆盖它的文本和图像名称。我的下一个问题是如何以某种方式动态设置它的框架(现在它是静态的),因为我需要 2x2 网格中的这 4 个按钮。

我正在尝试完全像这样创建按钮:https://imgur.com/a/dNhUGhc

我已经对此进行了编码,但它是静态的,在 ViewController 中我无法编辑(覆盖)这些标签和图像名称。如果我尝试重用这个 class 我会将它们放在同一个位置,因为框架设置完全相同。

我正在订阅 UIButton。class如果有更合适的东西请告诉我。

添加标签的代码

        // city label
        let cityRect = CGRect(x: 0, y: 20, width: buttonWidth, height: 25)
        let cityLabel = UILabel(frame: cityRect)
        cityLabel.text = "Label"
        cityLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
        cityLabel.textAlignment = .center
        addSubview(cityLabel)

添加图片的代码

        // image
        let imageView = UIImageView(image: UIImage(named: "something"))
        imageView.frame = CGRect(x: 0, y: 60, width: 40, height: 40)
        imageView.center.x = self.center.x - 20
        addSubview(imageView)

你们能帮帮我吗?谢谢

看来您需要做的是使用 IBOutlet。基本上,IBOutlet 将在您的代码(自定义 UIView 或 UIViewController 子类)中为您提供对您在 xib 或情节提要中设置的按钮的引用。然后您可以在运行时对其进行任何更改或调整。

查看 this 以了解有关 IBOutlets 以及如何在您的项目中设置它们的更多信息。