根据其内容(主要是其标题和图像)自动调整UIButton大小的最佳方法是什么?

时间:2019-06-10 16:56:16

标签: swift dynamic uibutton size

我编写了以下代码以生成自定义UIButton,打算在我的应用程序的不同位置使用它:

import UIKit

import ChameleonFramework

class CustomButton: UIButton {

    override init(frame: CGRect) {

        super.init(frame: frame)

    }

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

    }

    convenience init(buttonTitleTexForNormalState titleForNormalState: String, buttonTitleTextColourForNormalState normalTextColour: UIColor, buttonTitleTextColourForHighlightedState highlightedTextColour: UIColor, buttonTitleFontType fontType: String, buttonTitleFontSize fontSize: CGFloat, buttonBackgroundHexColourCode hexColour: String, buttonFrameCornerRadius cornerRadius: CGFloat, buttonFrameBorderWidth borderWidth: CGFloat, buttonFrameBorderColour borderColour: String, buttonBackgroundTransperancyAlphaValue transperancy: CGFloat, buttonTagNumber tagValue: Int, buttonTarget: Any?, buttonSelector: Selector, buttonImageForNormalState normalButtonImage: String) {

        self.init()

        setupButtonEssentials(buttonTitleTexForNormalState: titleForNormalState, buttonTitleTextColourForNormalState: normalTextColour, buttonTitleTextColourForHighlightedState: highlightedTextColour, buttonTitleFontType: fontType, buttonTitleFontSize: fontSize, buttonBackgroundHexColourCode: hexColour, buttonFrameCornerRadius: cornerRadius, buttonFrameBorderWidth: borderWidth, buttonFrameBorderColour: borderColour, buttonBackgroundTransperancyAlphaValue: transperancy, buttonTagNumber: tagValue, buttonTarget: buttonTarget, buttonSelector: buttonSelector, buttonImageForNormalState: normalButtonImage)

    }

    func setupButtonEssentials(buttonTitleTexForNormalState titleForNormalState: String, buttonTitleTextColourForNormalState normalTextColour: UIColor, buttonTitleTextColourForHighlightedState highlightedTextColour: UIColor, buttonTitleFontType fontType: String, buttonTitleFontSize fontSize: CGFloat, buttonBackgroundHexColourCode hexColour: String, buttonFrameCornerRadius cornerRadius: CGFloat, buttonFrameBorderWidth borderWidth: CGFloat, buttonFrameBorderColour borderColour: String, buttonBackgroundTransperancyAlphaValue transperancy: CGFloat, buttonTagNumber tagValue: Int, buttonTarget: Any?, buttonSelector: Selector, buttonImageForNormalState normalButtonImage: String) {

        setTitleColor(normalTextColour, for: .normal)

        setTitleColor(highlightedTextColour, for: .highlighted)

        titleLabel?.font = UIFont(name: fontType, size: fontSize)

        setTitle(titleForNormalState, for: .normal)

        backgroundColor = UIColor(hexString: hexColour)

        layer.cornerRadius = cornerRadius

        layer.borderWidth =  borderWidth

        layer.borderColor = UIColor(hexString: borderColour)?.cgColor

        showsTouchWhenHighlighted = true

        alpha = transperancy

        contentHorizontalAlignment = .center

        self.tag = tagValue

        addTarget(target, action: buttonSelector, for: .touchUpInside)

        if let buttonImage = UIImage(named: normalButtonImage) {

            setImage(buttonImage.withRenderingMode(.alwaysOriginal), for: .normal)

            contentMode = .scaleAspectFit

        }

        setShadow()

        translatesAutoresizingMaskIntoConstraints = false

    }

    private func setShadow() {

        layer.shadowColor = UIColor.black.cgColor

        layer.shadowOffset = CGSize(width: 0.0, height: 6.0)

        layer.shadowRadius = 8

        layer.shadowOpacity = 0.5

        clipsToBounds = true

        layer.masksToBounds = false

    }

    func shake() {

        let shake = CABasicAnimation(keyPath: "position")

        shake.duration = 0.1

        shake.repeatCount = 2

        shake.autoreverses = true

        let fromPoint = CGPoint(x: center.x-8, y: center.y)

        let fromValue = NSValue(cgPoint: fromPoint)

        let toPoint = CGPoint(x: center.x+8, y: center.y)

        let toValue = NSValue(cgPoint: toPoint)

        shake.fromValue = fromValue

        shake.toValue = toValue

        layer.add(shake, forKey: "position")

    }

}

下面的代码说明了一个示例,该示例是我在ViewController内从自定义UIButton类(如上所示)创建实例的例子:

import UIKit

import ChameleonFramework

class MainScreen: UIViewController, UINavigationBarDelegate {

    var newFileButton = CustomButton(buttonTitleTexForNormalState: "New...", buttonTitleTextColourForNormalState: .black, buttonTitleTextColourForHighlightedState: .blue, buttonTitleFontType: "Apple SD Gothic Neo", buttonTitleFontSize: 17, buttonBackgroundHexColourCode: "#B24B32", buttonFrameCornerRadius: 25, buttonFrameBorderWidth: 2, buttonFrameBorderColour: "#7AFFD2", buttonBackgroundTransperancyAlphaValue: 0.75, buttonTagNumber: 1, buttonTarget: self, buttonSelector: #selector(buttonPressed(sender:)), buttonImageForNormalState: "New File")

    override func viewDidLayoutSubviews() {

        super.viewDidLayoutSubviews()

        print("viewDidLayoutSubviews")

        view.addSubview(newFileButton)

        newFileButton.frame.size.width = 140

        newFileButton.frame.size.height = 100

    }

    @objc func buttonPressed(sender : UIButton) {

        if sender.tag == 1 {

            newFileButton.shake()

            guard let nextViewControllerToGoTo = storyboard?.instantiateViewController(withIdentifier: "NewFileButtonPressedTabController") else {

                print("NewFileButtonPressedTabController could not be presented")

                return

            }

            present(nextViewControllerToGoTo, animated: true, completion: nil)         

    }

}

但是,从上面的代码可以看出,我最终根据宽度和高度手动定义了自定义UIButton的大小。

我想知道Xcode是否可以根据其内容(主要是其标题和图像)为每个自定义UIButton找出最佳宽度和高度?

P.S:我尝试使用internalContent,但是对我来说不起作用。任何建议都非常感谢。

谢谢, 沙迪。

1 个答案:

答案 0 :(得分:0)

删除设置newFileButton.frame.size.width.height的代码,它应采用添加到其中的任何标题/图像的内容大小-至少要这样。如果您希望它大于此值,则只需设置内容插图(类似于内容周围的填充)。

在您按钮的课程中:

self.contentEdgeInsets = UIEdgeInsets(top: 10, left: 30, bottom: 10, right: 20)
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)