简体   繁体   English

iOS Swift Scrollview以编程方式设置框架位置

[英]iOS Swift Scrollview Set Frame Position Programmatically

I am have scrollview in my app. 我的应用程序中有scrollview。 By default y position of my scrollview is 80 . 默认情况下,我的滚动视图的y位置是80 In some locations I need to move y position of my scrollview to 0 . 在某些位置,我需要将滚动视图的y位置移到0 Here is the code 这是代码

@IBOutlet weak var ScrollView: UIScrollView!
override func viewDidLoad()
{
   super.viewDidLoad()
   self.ScrollView.delegate = self
   if(Position == "changed")
   {
      self.ScrollView.frame = CGRect(x: 0, y: 0, width: self.ScrollView.frame.size.width, height: self.ScrollView.frame.size.height)
   }
   else
   {
      self.ScrollView.frame = CGRect(x: 0, y: 80, width: self.ScrollView.frame.size.width, height: self.ScrollView.frame.size.height)
   }
}

But this code won't works. 但是此代码无效。

problem is simple your VC.view not updated in Viewdidload, so in here you need to move the UI updation on Viewdidappear or update the UI in main thread 问题很简单,您的VC.view没有在Viewdidload中更新,因此在这里您需要在Viewdidappear上移动UI更新或在主线程中更新UI

by default your self.ScrollView.frame is started in O position, so only check with != 默认情况下,您的self.ScrollView.frame是从O位置开始的,因此只能使用!=

override func viewDidLoad()
{
   super.viewDidLoad()
   self.ScrollView.delegate = self
   //self.ScrollView.frame = CGRect(x: 0, y: 0, width: self.ScrollView.frame.size.width, height: self.ScrollView.frame.size.height)
   if(Position != "changed")
   {
     DispatchQueue.main.async {
        self.ScrollView.frame = CGRect(x: 0, y: 80, width: self.ScrollView.frame.size.width, height: self.ScrollView.frame.size.height)
    }

   }

}

We will not able to set Scrollview Position in viewDidLoad() so Add those code in viewDidAppear() . 我们将无法在viewDidLoad()设置Scrollview Position,因此请在viewDidAppear()添加这些代码。 Final Code Here 最终代码在这里

override func viewDidAppear(_ animated: Bool)
{
     DispatchQueue.main.async
     {
          self.ScrollView.frame = CGRect(x: 0, y: 0, width: self.ScrollView.frame.size.width, height: self.ScrollView.frame.size.height + 80)
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM