用自己的宽度约束 Button

Constrain Button with its own width

真的很努力 constrain 我的 buttons

我想要的只是设置我的 2 buttonsheight35 并且他们的 width 应该是他们需要的任何东西.现在它看起来像这样(左右按钮):

我是这样设置的:

let communityButton: UIButton = {
    let v = UIButton()
    v.setImage(UIImage(systemName: "person.3.fill"), for: .normal)
    v.tintColor = UIColor.darkCustom
    v.imageView?.contentMode = .scaleAspectFill
    v.contentHorizontalAlignment = .fill
    v.contentVerticalAlignment = .fill
    v.translatesAutoresizingMaskIntoConstraints = false
    v.addTarget(self, action: #selector(communityButtonTapped), for: .touchUpInside)
    return v
}()

let profileButton: UIButton = {
    let v = UIButton()
    v.setImage(UIImage(systemName: "person.fill"), for: .normal)
    v.tintColor = UIColor.darkCustom
    v.imageView?.contentMode = .scaleAspectFill
    v.contentHorizontalAlignment = .fill
    v.contentVerticalAlignment = .fill
    v.translatesAutoresizingMaskIntoConstraints = false
    v.addTarget(self, action: #selector(profileButtonTapped), for: .touchUpInside)
    return v
}()

约束条件:

//contrain communityButton
communityButton.centerYAnchor.constraint(equalTo: bottomBar.centerYAnchor),
communityButton.centerXAnchor.constraint(equalTo: bottomBar.centerXAnchor, constant: -view.frame.width/3.5),
communityButton.heightAnchor.constraint(equalToConstant: 35),

// constrain profileButton
profileButton.centerYAnchor.constraint(equalTo: bottomBar.centerYAnchor),
profileButton.centerXAnchor.constraint(equalTo: bottomBar.centerXAnchor, constant: view.frame.width/3.5),
profileButton.heightAnchor.constraint(equalToConstant: 35),

这里约束的正确方法是什么?

您可能需要让 autoLayout 知道您希望宽度灵活。您可以通过在两个按钮定义中添加这一行来做到这一点:-

// Replace "myButton" with your buttons name in your case "v"
 myButton.autoresizingMask = [.flexibleWidth] 

编辑:- 由于您使用的是系统图像,如果您希望按钮看起来更大,则必须增加图像配置中的字体大小。通过使用您喜欢的字体大小添加配置来编辑您的图像。

例如:-


let communityButton: UIButton = {
    let v = UIButton()
//----
// NB: - Change the font size for bigger icons and viceversa
let imageSymbolConfiguration = UIImage.SymbolConfiguration(pointSize: 50, weight: .regular, scale: .large)
v.setImage(UIImage(systemName: "person.3.fill", withConfiguration: imageSymbolConfiguration), for: .normal)

// -----

    return v
}()


let profileButton: UIButton = {
    let v = UIButton()
    // ----
// NB: - Change the font size for bigger icons and viceversa
let imageSymbolConfiguration = UIImage.SymbolConfiguration(pointSize: 50, weight: .regular, scale: .large)
v.setImage(UIImage(systemName: "person.fill", withConfiguration: imageSymbolConfiguration), for: .normal)
     // ----
    return v
}()


解释:-

来自official documentation

"Symbol image configuration objects include details such as the point size, scale, text style, weight, and font to apply to your symbol image. The system uses these details to determine which variant of the image to use and how to scale or style the image."