I want to programmatically set multiple alignment combinations for my button title, like so:
The easiest way I found to do this was to add two
UILabel
s as subviews of my custom UIButton
and set autolayout constraints accordingly.
However, I can't figure out how to make my labels behave the same way as a button title would (namely having its alpha altered when a button tap occurs).
I have tried setting their alpha property in a target-action method for .touchUpInside
but since they're not attached to the button state, they won't change their alpha back to normal when the user ends tapping the button.
class Button: UIView {
var leftButton = UIButton(type: .roundedRect)
var rightButton = UIButton(type: .roundedRect)
init() {
super.init(frame: .zero)
createButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createButton()
}
func createButton() {
self.backgroundColor = UIColor.cyan
self.layer.borderWidth = 0.5
self.layer.borderColor = UIColor.blue.cgColor
self.addSubview(leftButton)
self.addSubview(rightButton)
leftButton.setTitle("left", for: .normal)
leftButton.setTitleColor(UIColor.black, for: .normal)
leftButton.layer.borderColor = UIColor.yellow.cgColor
leftButton.layer.borderWidth = 0.5
leftButton.translatesAutoresizingMaskIntoConstraints = false
leftButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
leftButton.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
leftButton.trailingAnchor.constraint(lessThanOrEqualTo: rightButton.leadingAnchor).isActive = true
leftButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
rightButton.setTitle("right", for: .normal)
rightButton.layer.borderColor = UIColor.green.cgColor
rightButton.layer.borderWidth = 0.5
rightButton.setTitleColor(UIColor.black, for: .normal)
rightButton.translatesAutoresizingMaskIntoConstraints = false
rightButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
rightButton.leadingAnchor.constraint(greaterThanOrEqualTo: leftButton.trailingAnchor).isActive = true
rightButton.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
rightButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
leftButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
rightButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
}
func buttonTapped() {
print("button tapped")
}