Multiline UIButton and autolayout

后端 未结 16 1518
无人共我
无人共我 2020-12-03 13:08

I have created a view controller that looks like this:

\"enter

I want the two

16条回答
  •  醉酒成梦
    2020-12-03 13:40

    Complete class in Swift 3 - based on @Jan, @Quantaliinuxite and @matt bezark:

    @IBDesignable
    class MultiLineButton:UIButton {
    
        //MARK: -
        //MARK: Setup
        func setup () {
            self.titleLabel?.numberOfLines = 0
    
            //The next two lines are essential in making sure autolayout sizes us correctly
            self.setContentHuggingPriority(UILayoutPriorityDefaultLow+1, for: .vertical)
            self.setContentHuggingPriority(UILayoutPriorityDefaultLow+1, for: .horizontal)
        }
    
        //MARK:-
        //MARK: Method overrides
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setup()
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            setup()
        }
    
        override var intrinsicContentSize: CGSize {
            return self.titleLabel!.intrinsicContentSize
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            titleLabel?.preferredMaxLayoutWidth = self.titleLabel!.frame.size.width
        }
    }
    

提交回复
热议问题