Samek
Samek

Reputation: 3

Button with multiple accessible labels and images in Swift

I need to create custom button class, reuse it 4 times and I also need to override its text and image name. My next problem is how to set its frame somehow dynamically (now it is static), because I need this 4 buttons in grid 2x2.

I'm trying to create button exactly like this: https://i.sstatic.net/KTi2Z.jpg.

I have coded this but it is static and in ViewController I can't edit (override) these labels and image name. And if I tried to reuse this class I would have them in the same spot, because frame settings is exactly the same.

I'm subclassing UIButton. If something more suitable exists just let me know.

Code for adding label

        // 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)

Code for adding image

        // 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)

Can you guys help me? Thanks

Upvotes: 0

Views: 367

Answers (1)

adeiji
adeiji

Reputation: 570

It looks like what you need to do is use an IBOutlet. Basically, an IBOutlet will give you a reference within your code (custom UIView or UIViewController subclass) to the button that you've setup in xib or storyboard. Then you can make any changes or adjustments that you want to it at runtime.

Check this out to learn more about IBOutlets and how to set them up in your project.

Upvotes: 1

Related Questions