gpt4 book ai didi

ios - 如何在 UIScrollView 上修复 UIButton?

转载 作者:行者123 更新时间:2023-12-01 18:40:11 24 4
gpt4 key购买 nike

我的 UIScrollView 上有一个 UIButton,当我缩放 ScrollView 时,按钮位置不固定……有没有办法让它固定在一个位置?

最佳答案

从 iOS 11 开始,UIScrollView有一个名为 frameLayoutGuide 的实例属性. frameLayoutGuide有以下声明:

var frameLayoutGuide: UILayoutGuide { get }

The layout guide based on the untransformed frame rectangle of the scroll view.



Use this layout guide when you want to create Auto Layout constraints that explicitly involve the frame rectangle of the scroll view itself, as opposed to its content rectangle.



以下 Swift 5.1/iOS 13 UIViewController实现展示了如何使用 frameLayoutGuide为了使 UIButton 居中在 UIScrollView 内.

import UIKit

class ViewController: UIViewController {

let scrollView = UIScrollView()
let button = UIButton(type: .system)
let imageView = UIImageView(image: UIImage(named: "LargeImage"))

override func viewDidLoad() {
super.viewDidLoad()

// Set scrollView constraints
scrollView.contentInsetAdjustmentBehavior = .never
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])

// Set imageView constraints
scrollView.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor),
imageView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
imageView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor)
])

// Set button constraints (centered)
button.setTitle("Button", for: .normal)
scrollView.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: scrollView.frameLayoutGuide.centerXAnchor),
button.centerYAnchor.constraint(equalTo: scrollView.frameLayoutGuide.centerYAnchor)
])
}

}

关于ios - 如何在 UIScrollView 上修复 UIButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44525763/

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