gpt4 book ai didi

ios - ScrollView Autolayout 使用 Label 但不使用 Custom Control

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:32:14 28 4
gpt4 key购买 nike

我正在开发一个项目,该项目在 UIScrollView 中有一个自定义分段控件。我想使用自动布局来定位分段控件。我正在使用这个项目作为我的模型:https://github.com/honghaoz/UIScrollView-and-AutoLayout

import UIKit

class ViewController: UIViewController {

let scrollView = UIScrollView()
var screenBounds: CGRect { return UIScreen.main.bounds }

override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}

override func viewDidLoad() {
super.viewDidLoad()

// Setup scroll view

scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.backgroundColor = UIColor(red:20/255.0, green:119/255.0, blue:61/255.0, alpha:255/255.0)
view.addSubview(scrollView)

// Setup constraints
var views: [String: UIView] = [
"scrollView": scrollView
]

var constraints = [NSLayoutConstraint]()

// External constraints
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: views)


// Internal constraints
// Note: to let scrollView determines its contentSize, four edges should be explicitly specified
let v1 = newLabelWithText("v1 v1 v1 v1 v1 v1 v1 v1 v1 v1")
scrollView.addSubview(v1)
views["v1"] = v1

//Create Segmented Control
let segmentedB = YSSegmentedControl(
//Set Frame in Callback (Required)
frame: CGRect(x: 0, y: 0, width: 400, height: 60),
titles: [
"Yes",
"No"
],
action: {
control, index in
print ("segmented did pressed \(index)")
})
scrollView.addSubview(segmentedB)
views["v4"] = segmentedB

let v2 = newLabelWithText("v2 v2 v2 v2 v2")
views["v2"] = v2


let v3 = newLabelWithText("v3 v3 v3 v3 v3")
views["v3"] = v3
scrollView.addSubview(v3)

// Horizontal, fully specified
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-200-[v4]-300-|", options: .alignAllLastBaseline, metrics: nil, views: views)
// Vertically, fully specified
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-200-[v3]-1000-|", options: .alignAllLeading, metrics: nil, views: views)

NSLayoutConstraint.activate(constraints)
print("scrollView.contentSize: \(scrollView.contentSize)")
}
}

出于某种原因,自动布局在文本标签上工作得很好,但在分段控件上却不行。回调要求我为 CGRect 输入参数,因此我只设置宽度和高度并将位置参数保留为零。这在没有 ScrollView 时有效,但现在无效。

另外,我没有在这个项目中使用 Storyboard。所有约束和 View 均以编程方式创建。

感谢任何帮助。谢谢

最佳答案

我认为你应该在添加约束之前添加这一行

segmentedB.translatesAutoresizingMaskIntoConstraints = false

无论何时以编程方式添加约束,都应将此属性设置为 false,以使约束对 View 生效

关于ios - ScrollView Autolayout 使用 Label 但不使用 Custom Control,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45459815/

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