无法在UIStackView中设置按钮图像

时间:2017-09-26 16:04:57

标签: ios uistackview swift4 xcode9

我有UICollectionViewCell,其UIStackView填充整个单元格。

UIStackView内部,我正在尝试添加subviews,但我在这里遇到了两个问题。

首先,我看不到UIStackView被添加到cell,甚至将堆栈视图背景颜色设置为它不显示的其他颜色。

第二个问题是我的应用 - 在这种情况下,当我将按钮图像实例化为Today Extension Widget

时,button.setImage(:_)崩溃了

以下是代码:

@objc lazy var composeButton: UIButton = {
    let button = UIButton(type: .system)
    let image = #imageLiteral(resourceName: "compose_icon").withRenderingMode(.alwaysOriginal)
    button.setImage(image, for: .normal)
    button.addTarget(self, action: #selector(didTapCompose), for: .touchUpInside)
    return button
}()

let stackview = UIStackView(arrangedSubviews: [composeButton, reloadButton])
stackview.distribution = .fillEqually
stackview.axis = .horizontal
addSubview(stackview)
stackview.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddinfLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)



extension UIView {
    /// Anchor a specific view to a superview
    @objc func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddinfLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat) {
        translatesAutoresizingMaskIntoConstraints = false
        if let top = top {
            topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
        }
        if let left = left {
            leftAnchor.constraint(equalTo: left, constant: paddinfLeft).isActive = true
        }
        if let bottom = bottom {
            bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
        }
        if let right = right {
            rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
        }
        if width != 0 {
            widthAnchor.constraint(equalToConstant: width).isActive = true
        }
        if height != 0 {
            heightAnchor.constraint(equalToConstant: height).isActive = true
        }
    }

    /// Rounds the corners of a UIView object
    /// parameters: corners - the corners to round (upperLeft, upperRight, lowerLeft, lowerRight);
    ///             radiud - the desired cornerRadius to apply to the desired corners
    @objc func roundCorners(corners:UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}

该应用程序在此行崩溃

  

button.setImage(image,for:。normal)

崩溃时出现SIGABRT错误,如下图所示。

有没有人在这里发现问题?

SIGABRT

1 个答案:

答案 0 :(得分:1)

由于这是Today Extension Widget的一部分,请确保您已将该图片包含在该构建目标中。

未来的调试提示:当您看到一个错误时,"确实不应该发生,"试着一步一步地思考。在这种情况下,虽然.setImage行似乎是罪魁祸首,但如果您检查了let image =行的有效性,则可能节省了一点时间。