gpt4 book ai didi

ios - 向以编程方式添加的 subview 添加右对齐约束

转载 作者:行者123 更新时间:2023-11-30 12:16:19 27 4
gpt4 key购买 nike

我正在尝试向“UITableViewCell”添加右对齐的分段控件,如下所示:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "mycell")
// ...
addSegmentedControlToCell(cell)
// ...

然后

func addSegmentedControlToCell(_ cell:UITableViewCell){
let items = ["One","Two"]
let unitControl = UISegmentedControl(items: items)
unitControl.selectedSegmentIndex = 0
let maxWd = cell.frame.size.width
let maxHt = cell.frame.size.height
let padding:CGFloat = 5
unitControl.frame = CGRect(x:maxWd/2, y:padding, width:maxWd/2, height: maxHt-padding*2)
unitControl.addTarget(self, action: #selector(SettingsTableViewController.unitControlValueDidChange(_:)), for: .valueChanged)
cell.addSubview(unitControl)
}

这在我的默认设备 iPhone 6 上运行良好。但是当我在宽度较小的设备(例如 iPhone 5)上运行此应用程序时,以编程方式添加的 Segment Control 会接收 50% 的单元格宽度 (cell.frame.size.width/2) 看起来比宽度的 50% 大得多,并且延伸到单元格 View 端口下方的右侧。

这是因为自动布局和限制,正如我所看到的,因为 iPhone 5 单元格 View 的大小发生了调整。所以我试图向我的新段控制添加一个约束,该约束因应用程序崩溃而失败。请注意,我还不太擅长以编程方式添加约束。

    let widthContr = NSLayoutConstraint(item: unitControl,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: cell,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: 0.5)
cell.addConstraints([widthContr])

如何正确右对齐 subview (段控制)以获得正确的单元格大小?

最佳答案

您可以像这样设置约束:

yourView.rightAnchor.constraint(equalTo: yourCell.rightAnchor, constant: -10).isActive = true

或者:

yourView.heightAnchor.constraint(equalToConstant: 50).isActive = true

但请确保包含以下代码:

yourSegmentedControl.translatesAutoresizingMaskIntoConstraints = false

关于ios - 向以编程方式添加的 subview 添加右对齐约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45401534/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com