0

I'm using this code to customize UIButtons on my main ViewController and have placed it in it's own separate .swift file to be referenced wherever a UIButton exists. I want to be able to modify the properties of the MyCustomButton from within my main ViewController after a button is pressed. For example, I press a button that's using the properties from MyCustomButton and its color changes.

I'm just getting into swift and am not greatly familiar with it's ins and outs quite yet. Any help is appreciated.

import Foundation
import UIKit

class MyCustomButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = 25;
        self.layer.borderColor = UIColor.blackColor().CGColor
        self.layer.borderWidth = 3
        self.backgroundColor = UIColor.redColor()
        self.tintColor = UIColor.whiteColor()
        self.setTitle("", forState: UIControlState.Normal)
        self.titleLabel?.numberOfLines = 0
        self.titleLabel?.textAlignment = NSTextAlignment.Center
    }
}
npburns224
  • 632
  • 7
  • 11
  • Check that question: http://stackoverflow.com/questions/26086902/swift-how-to-create-a-nscoding-subclass-and-call-it-from-another-class –  Jan 05 '16 at 18:55

3 Answers3

0

You can try to override layoutSubviews method:

override func layoutSubviews() {
    super.layoutSubviews()

    if self.state == UIControlState.Highlighted {
        // DO WHAT YOU WANT
    } else {
        // RESET TO NORMAL
    }
}
Flexoid
  • 50
  • 8
0

KVO or delegate protocol (Swift) would work! Either of these would allow you to manipulate the properties of your UI elements when a specific action occurs.

ackerman91
  • 549
  • 3
  • 13
0

If you want to create new class and change button default behaivour, you should override functions like this one

override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
    super.pressesBegan(presses, withEvent: event)
    // add your implementation here
}

//    func pressesCancelled
//    func pressesChanged
//    func pressesEnded
//    etc.

But if you just want to change button properties on button tap, you can do it on button callback method:

    override func viewDidLoad() {
        super.viewDidLoad()

        let button   = UIButton(type: UIButtonType.System) as UIButton
        button.frame = CGRectMake(100, 100, 100, 100)
        button.setTitle("My Button", forState: UIControlState.Normal)
        button.addTarget(self, action: "someAction:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)
    }

    func someAction(sender: UIButton) {
        print("My Button tapped")
        sender.setTitle("Now Tapped", forState: UIControlState.Normal)
    }
shpasta
  • 1,913
  • 15
  • 21