如何以编程方式向 stackView 添加约束

发布于 2025-01-10 16:44:07 字数 1452 浏览 4 评论 0原文

我以编程方式创建了一个带有 UISegmentedControl 的 stackView 和一个带有 MKMapView 的 Map 。我使用 CGRect 来调整 stackView 的框架大小并将其放置在界面中,但是当我切换设备模拟器时,stackView 会移动,因为它没有任何约束。我通常使用 StoryBoard 为任何内容添加约束,但我自己从未以编程方式完成过。我在 Stack Overflow 中看到了其他示例,但到目前为止,它对我正在尝试做的事情没有帮助。 这是我的代码,显示了如何在 viewDidLoad() 中显示它。如果有人可以解释如何以编程方式添加约束,以便 stackView 覆盖屏幕 Y 轴的 1/4:547,谢谢。

import UIKit
import MapKit

class SampleViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()
    
    let paddedStackView = UIStackView(arrangedSubviews: [segmentedControl])
    paddedStackView.layoutMargins = .init(top: 12, left: 12, bottom: 6, right: 12)
    paddedStackView.isLayoutMarginsRelativeArrangement = true
    
    let stackView = UIStackView(arrangedSubviews: [
        paddedStackView, map
        ])
    stackView.axis = .vertical
    view.addSubview(stackView)
    
    stackView.frame =  CGRect(x: 0, y: 547, width: 390, height: 350)

}

let map = MKMapView()

let segmentedControl:UISegmentedControl = {
    let sc = UISegmentedControl(items: ["Arriving", "Leaving"])
    sc.selectedSegmentIndex = 0
    sc.addTarget(self, action: #selector(handleSegmentControl), for: .valueChanged)
    return sc
}()

  @objc func handleSegmentControl(){
    
    switch segmentedControl.selectedSegmentIndex {
    case 0:
        print("Entered Destination")
    case 1:
        print("Exited Destination")
    default:
        print("Error")
    }

}

I programmatically created a stackView with a UISegmentedControl and a Map with a MKMapView. I am using CGRect to size and place the frame of the stackView in the interface but when I switch the device simulator the stackView moves since it does not have any constraints. I usually use the StoryBoard to add constraints to anything but have never programmatically done it my self. I have seen other examples here in Stack Overflow but so far It doesn't help with what it is that I am trying to do.
Here is my code showing how I am displaying it in the viewDidLoad(). If someone could explain how to add constraints programmatically so that the stackView covers 1/4 of the screen Y axis:547 please and thank you.

import UIKit
import MapKit

class SampleViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()
    
    let paddedStackView = UIStackView(arrangedSubviews: [segmentedControl])
    paddedStackView.layoutMargins = .init(top: 12, left: 12, bottom: 6, right: 12)
    paddedStackView.isLayoutMarginsRelativeArrangement = true
    
    let stackView = UIStackView(arrangedSubviews: [
        paddedStackView, map
        ])
    stackView.axis = .vertical
    view.addSubview(stackView)
    
    stackView.frame =  CGRect(x: 0, y: 547, width: 390, height: 350)

}

let map = MKMapView()

let segmentedControl:UISegmentedControl = {
    let sc = UISegmentedControl(items: ["Arriving", "Leaving"])
    sc.selectedSegmentIndex = 0
    sc.addTarget(self, action: #selector(handleSegmentControl), for: .valueChanged)
    return sc
}()

  @objc func handleSegmentControl(){
    
    switch segmentedControl.selectedSegmentIndex {
    case 0:
        print("Entered Destination")
    case 1:
        print("Exited Destination")
    default:
        print("Error")
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

[浮城] 2025-01-17 16:44:07

如果您的问题是如何转换它:

stackView.frame =  CGRect(x: 0, y: 547, width: 390, height: 350)

并使高度屏幕的1/4而不是350

将此请求转换为自动布局约束将像这样

private func configureStackView()
{
    let paddedStackView = UIStackView(arrangedSubviews: [segmentedControl])
    paddedStackView.layoutMargins = .init(top: 12,
                                          left: 12,
                                          bottom: 6,
                                          right: 12)
    
    paddedStackView.isLayoutMarginsRelativeArrangement = true
    
    let stackView = UIStackView(arrangedSubviews: [paddedStackView, map])
    stackView.axis = .vertical
    view.addSubview(stackView)
    
    // AUTO LAYOUT
    
    // This is important for using auto layout
    // Setting this to false means the frame is ignored
    // So sizing and positioning should be set by NSLayoutConstraints
    stackView.translatesAutoresizingMaskIntoConstraints = false
    
    // Add the view to its parent before adding any constraints
    view.addSubview(stackView)
    
    // Add constraints equivalent to:
    // CGRect(x: 0, y: 547, width: 390, height: 350)
    view.addConstraints([
        // this is x origin
        stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        
        // this is y origin
        stackView.topAnchor.constraint(equalTo: view.topAnchor,
                                       constant: 547),
        
        // this is the width
        stackView.widthAnchor.constraint(equalToConstant: 390),
        
        // this is height, thanks to @flanker for this update
        stackView.heightAnchor.constraint(equalTo: view.heightAnchor,
                                          multiplier: 0.75)
    ])
}

这应该给您您正在寻找的东西。

话虽如此,您可能想查看这个SO线程因为有不同的方法可以以编程方式添加自动布局约束,所以看看您更喜欢哪种方式

使用屏幕截图更新

上面的配置给出了类似的内容

以编程方式创建具有自动布局约束的 UIStackView swift iOS

If your question is how to convert this:

stackView.frame =  CGRect(x: 0, y: 547, width: 390, height: 350)

and make the height 1/4 of the screen instead of 350

Converting this request into auto layout constraints would go something like this

private func configureStackView()
{
    let paddedStackView = UIStackView(arrangedSubviews: [segmentedControl])
    paddedStackView.layoutMargins = .init(top: 12,
                                          left: 12,
                                          bottom: 6,
                                          right: 12)
    
    paddedStackView.isLayoutMarginsRelativeArrangement = true
    
    let stackView = UIStackView(arrangedSubviews: [paddedStackView, map])
    stackView.axis = .vertical
    view.addSubview(stackView)
    
    // AUTO LAYOUT
    
    // This is important for using auto layout
    // Setting this to false means the frame is ignored
    // So sizing and positioning should be set by NSLayoutConstraints
    stackView.translatesAutoresizingMaskIntoConstraints = false
    
    // Add the view to its parent before adding any constraints
    view.addSubview(stackView)
    
    // Add constraints equivalent to:
    // CGRect(x: 0, y: 547, width: 390, height: 350)
    view.addConstraints([
        // this is x origin
        stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        
        // this is y origin
        stackView.topAnchor.constraint(equalTo: view.topAnchor,
                                       constant: 547),
        
        // this is the width
        stackView.widthAnchor.constraint(equalToConstant: 390),
        
        // this is height, thanks to @flanker for this update
        stackView.heightAnchor.constraint(equalTo: view.heightAnchor,
                                          multiplier: 0.75)
    ])
}

This should give you what you are looking for.

With that being said, you probably want to check out this SO thread as there are different ways to add auto layout constraints programmatically so see which way you prefer

Update with screenshot

The above configuration gives something like this

Programmatically create UIStackView with auto layout constraints swift iOS

棒棒糖 2025-01-17 16:44:07
    //MARK: UIStackView
    
    let stackview = UIStackView()
    stackview.axis = .vertical
    stackview.spacing = 2
    stackview.distribution = .fill
    
    //MARK: Stackview Elements
    let view_left = UIView()
    let view_right = UIView()
    
    //MARK: initial added View
    stackview.addArrangedSubview(view_left)
    stackview.addArrangedSubview(view_right)
    
    //MARK: remove Run time stack elements
    
    for view in stackview.subviews {
        view.removeFromSuperview()
    }
    
   //MARK: Again assign values Run time
    
    stackview.insertArrangedSubview(view_right, at: 0)
    stackview.insertArrangedSubview(view_left, at: 1)
    //MARK: UIStackView
    
    let stackview = UIStackView()
    stackview.axis = .vertical
    stackview.spacing = 2
    stackview.distribution = .fill
    
    //MARK: Stackview Elements
    let view_left = UIView()
    let view_right = UIView()
    
    //MARK: initial added View
    stackview.addArrangedSubview(view_left)
    stackview.addArrangedSubview(view_right)
    
    //MARK: remove Run time stack elements
    
    for view in stackview.subviews {
        view.removeFromSuperview()
    }
    
   //MARK: Again assign values Run time
    
    stackview.insertArrangedSubview(view_right, at: 0)
    stackview.insertArrangedSubview(view_left, at: 1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文