首页 > 解决方案 > 使用swift在scrollview内的stackview中更改uibutton中的标题

问题描述

你能给我一些帮助,为什么按钮标题的填充不起作用,好吗?

我有下面的代码,我从那里更新按钮的标题 n 次。按钮位于水平滚动视图内。在滚动视图里面我有一个堆栈视图。从卷轴外部,我更新了标题,并且填充超出了我的控制范围。

问题如下:如果我为按钮提供了一个巨大的标题,然后我更改为一个短标题,则填充不会像我在下面的代码中确定的那样更新。

    private func setupActionButtons(index: Int = 0, title: String = "") {
    
    allButtons[index].layer.cornerRadius = allButtons[0].bounds.height/2
    allButtons[index].layer.borderWidth = 1
    allButtons[index].layer.borderColor = UIColor.borderShortcutButton.cgColor
    allButtons[index].setTitleColor(.psGreyValueLabelFilled, for: .normal)
    if title != "" {
        allButtons[index].setTitle(title, for: .normal)
    }
    allButtons[index].titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    allButtons[index].contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 15)
    allButtons[index].imageEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
    
    allButtons[index].imageView?.contentMode = .scaleAspectFit
    allButtons[index].setImage(uiImage, for: .normal)
    allButtons[index].semanticContentAttribute = UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft ? .forceLeftToRight : .forceRightToLeft
    
    allButtons[index].titleLabel?.font = UIFont.systemFont(ofSize: buttonFontSize, weight: UIFont.Weight.semibold)
    
    allButtons[index].tag = index
    allButtons[index].addTarget(self, action: #selector(self.handleSelectOption(sender:)), for: .touchUpInside)
    
}

更好地解释:当我在stackview中为两个按钮添加具有相似宽度的标题,然后我将其中一个按钮的标题更改为更小的宽度时,另一个按钮的宽度更大,填充更大,另一个我改变了排列正确。

标签: swiftuiscrollviewuibuttonpaddinguistackview

解决方案


问题是将堆栈视图设置DistributionFill Proportionally

随着堆栈视图设置为Fill问题消失。

作为旁注:忘记你听说过Fill Proportionally......这是堆栈视图中最容易被误解和误用的设置,除非你确切地知道它是如何工作的以及你想要使用它的确切原因,否则你不会得到你想要的布局.


推荐阅读