iOS/이슈

[iOS Issue] Custom UIButton에서 inset 사용 시 Button title이 제대로 안 보이는 현상

Sky Titan 2021. 1. 26. 14:12
728x90

 rounded한 Custom Button을 사용해서 만들던 중, 내부 여백을 주기 위해 inset을 사용했는데 title이 ...으로 축약되면서 제대로 보이지 않는 현상이 생겼다.

  원인

  1. Button의 size를 결정할 수 있는 constraint을 주지 않음
  2. Button의 intrinsic size가 inset을 고려하지 않고 결정됨

 

해결

  1. 버튼의 크기가 유동적으로 변할 수 있게 leading에 less than 제약을 걸어준다.
  2. UIButton의 intrinsicContentSize 프로퍼티를 override해서 inset만큼 크기를 늘려준다.

import UIKit

class CustomButton: UIButton {
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        
        setRoundedBorder()
    }
    
    private func setRoundedBorder() {
        layer.cornerRadius = 15
        layer.borderWidth = 1
        layer.borderColor = UIColor.black.cgColor
    }
    
    // When use titleEdgeInset, need to expand button size widely
    override var intrinsicContentSize: CGSize {
        return CGSize(width: super.intrinsicContentSize.width + contentEdgeInsets.left + contentEdgeInsets.right + titleEdgeInsets.left + titleEdgeInsets.right,
                      height: super.intrinsicContentSize.height + contentEdgeInsets.top + contentEdgeInsets.bottom + titleEdgeInsets.top
                        + titleEdgeInsets.bottom )
    }

}

 

결과

728x90