In which function of my uiviewcontroller should I set position and size of programmatically created uiviews?

时间:2016-04-15 11:07:43

标签: ios objective-c iphone uiview uiviewcontroller

I have a view controller which I created with IB, It has a CollectionView that will load some data, during loading process I want to show an activity indicator. For that I set the center property on activityIndicator to be equal to the center property of collectionView.

the problem is that I don't know on which method of viewController should I do this. I tried it first inside viewDidLoad method but inside this method the frame of collectionView is equal to what it was inside IB and activityIndicator can't be set properly.

So my questions are :

  1. I want to know where should I do this kind of positioning of UIView objects
  2. When does ios sdk give the views the sizes they should have in respect of the device the app is running on not the IB.
  3. What happens inside of viewController methods like viewDidLoad and viewWillLayoutSubviews when we call those methods on super object of viewController like [super viewDidLoad]

3 个答案:

答案 0 :(得分:0)

所有与绘图相关的操作都应在application’s main thread上执行,然后您可以在viewDidLoad或任何其他委托功能中创建。

线程注意事项

必须在主线程上对应用程序的用户界面进行操作。因此,您应该始终从应用程序主线程中运行的代码调用UIView类的方法。这可能不是绝对必要的唯一时间是创建视图对象本身,但所有其他操作应该在主线程上发生。

dispatch_async(dispatch_get_main_queue(),{

// Call function here.

 })

供参考[UIView]:  (https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html

答案 1 :(得分:0)

1。我想知道我应该在哪里进行UIView对象的这种定位

如果你正在使用界面构建器,你应该使用autolayout将它们定位在界面构建器中,否则主线程上的任何地方都可以。有时您可能需要调用[self.view setNeedsLayout] / [self.view setNeedsDisplay],具体取决于您所做的更改时间,但最终对于正常CGRectMake次调用您没问题。

2。 ios sdk何时向视图提供应用程序运行的设备尺寸,而不是IB。

UIView有一个名为layoutSubviews的方法 否则,对于VC,请查看viewWillLayoutSubviewsviewDidLayoutSubviews调用

的任意一侧

3。当我们在viewController的超级对象上调用那些方法时,viewController方法(如viewDidLoad和viewWillLayoutSubviews)会发生什么,例如[super viewDidLoad]

一般来说,对于这些方法,你应该在覆盖的顶部调用super来获取下面发生的任何事情。然后继续工作......

-(void)viewDidLoad
{
    [super viewDidLoad];

    UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, self.view.bounds.size.width, 100.0f)];
    myView.backgroundColor = [UIColor redColor];
    myView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:myView];
}

以上将完全正常。无需viewDidAppear。查看自动布局和自动调整大小。我个人认为在代码中工作而不是界面构建工具更好......但这是个人选择。

答案 2 :(得分:0)

你应该使用MBProgressHud伟大的图书馆来显示活动指标。从github下载这个。在项目中拖放MBProgressHud.m[MBProgressHUD showHUDAddedTo:self.view animated:YES];。在您的班级中导入.h文件。

然后致电dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ // Do something... //using main thread to hide immediately dispatch_async(dispatch_get_main_queue(), ^{ [MBProgressHUD hideHUDForView:self.view animated:YES]; }); });

并在想要解散或隐藏时打电话,

const fse = require('fs-extra');
fse.copySync('../util/various/a.html', '../release');
fse.copySync('../util/various/b.html', '../release');

它会自动保持中心和其他类型的东西。就是这样。希望这会有所帮助。 :)