ilovecomputer
ilovecomputer

Reputation: 4708

Subview of customized UIButton wasn't at the right postition

I added a subView to my customized UIButton. Then I created a button subclass to my customized UIButton from Storyboard, but the bounds of the subView wasn't set correctly.

Expected:

enter image description here

What I got instead:

enter image description here

Code of my customized UIButton, quite simple:

import UIKit
@IBDesignable

class RoundShadowButton: UIButton {

    var backLayer: UIView!

    override func drawRect(rect: CGRect) {
        setup()
    }

    func setup() {
        backLayer = UIView()

        //add the subView
        backLayer?.bounds = bounds
        backLayer!.layer.cornerRadius = 10.0
        backLayer?.layer.masksToBounds = false
        backLayer!.layer.borderColor = UIColor.redColor().colorWithAlphaComponent(0.3).CGColor
        backLayer!.layer.borderWidth = 1.0
        backLayer.clipsToBounds = false
        addSubview(backLayer)

        //add shadow to layer of UIButton
        layer.shadowColor = UIColor.blackColor().CGColor
        imageEdgeInsets = UIEdgeInsetsMake(9, 32, 9, 32)
        layer.shadowOffset = CGSizeMake(0.0, 0.5)
        layer.shadowRadius = 1.0
        layer.shadowOpacity = 0.7
        layer.masksToBounds = false
        clipsToBounds = false
    }

How can I fix the problem?

Upvotes: 1

Views: 55

Answers (1)

You will override method "func layoutSubviews()" to set frame of your backLayer subview, something like this

override func layoutSubviews() 
{
    super.layoutSubviews()
    backLayer.frame = bounds
}

Why did you do setup in "drawRect(rect: CGRect)" no in the "init?(coder aDecoder: NSCoder)" or "func awakeFromNib()"?

Upvotes: 1

Related Questions