首页 > 解决方案 > UICollectionViewCell 锚/约束男生错误

问题描述

我有一个超大标签(我需要截断)和 UIStackView 中的 UISwitch 的布局问题。UI渲染明显不正确,看截图https://www.dropbox.com/s/ankoovfh874kgy7/AlignmentTruncation.jpg

显然,只是太晚了,我已经盯着这个太久了。如果有人可以帮助我解决这个男生错误,我将不胜感激。

开发环境 Xcode 10.2 (10E125),macOS Mojave 10.14.5 Beta。

谢谢

麦克风


class SwitchableOptionCell : UICollectionViewCell {

    let switchView : UISwitch = {
        let sv = UISwitch()
        return sv
    }()

    let labelView : UILabel = {
        let lv = UILabel()
        lv.backgroundColor = .red
        lv.text = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog"
        lv.lineBreakMode = .byTruncatingTail
        return lv
    }()

    override init(frame : CGRect)
    {
        super.init(frame : frame)

        let sv = UIStackView(arrangedSubviews: [labelView, switchView])
        sv.spacing = 12
        sv.alignment = .center

        addSubview(sv)

        sv.translatesAutoresizingMaskIntoConstraints = false

        sv.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        sv.leadingAnchor.constraint(equalTo : self.leadingAnchor, constant: 16).isActive = true
        sv.bottomAnchor.constraint(equalTo : self.bottomAnchor).isActive = true
        sv.trailingAnchor.constraint(equalTo : self.trailingAnchor, constant: -16).isActive = true
    }

    required init?(coder aDecoder : NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }
}

标签: swiftuicollectionviewcell

解决方案


只需尝试将 sv.alignment = .center 更改为 sv.alignment = .fill 或 sv.alignment = .fillProportionaly

问题可能与 uiswitch 有关。他不知道他的实际宽度。因此,您可以尝试为具有宽度约束的 uiswitch 创建一些容器


推荐阅读