iOS:动态显示/隐藏UI元素

时间:2015-07-27 16:48:05

标签: ios objective-c iphone uitableview

我的应用程序在中心列中有一个UITableView结果,顶部有一个小搜索栏。我想动态添加/删除一个按钮,说明"重置搜索"并将其固定在视图的顶部。

有几种方法可以解决这个问题,我担心他们看起来既丑陋又丑陋。即:

  • 在情节提要编辑器中添加按钮,并在代码中显示/隐藏它。问题是我已经在故事板中以这种方式指定了一堆视图,因此定位/选择它们是一个巨大的痛苦,因为它们相互重叠。

  • 在代码中添加按钮。除了现在我的UI在两个地方指定:故事板中的内容,以及代码中发生的其他修改。

这样做的标准方法是什么?当我有按钮/对话框等时,如何防止我的故事板变得一团糟。需要动态显示/隐藏?

3 个答案:

答案 0 :(得分:1)

我的第一个答案是首先不要使用故事板。但是,我知道在这种情况下没有帮助。

如果我是你,我会做选项2.这个按钮只有一个,它有一个特定的用例。在代码中指定它并不会有什么坏处。

是以下内容
.h
@property (nonatomic, strong) UIButton *resetButton;

.m
//I'm guessing you're using a VC, so I'd put this in viewDidLoad

self.resetButton = [[UIButton alloc]initWithFrame:YOUR FRAME];
self.resetButton.alpha = 0.0;
//any other styling
[self.view addSubview:self.resetButton];
self.resetButton addTarget:self action:@selector(onReset) forControlEvents:UIControlEventTouchUpInside];

//and then add these three methods

- (void)onReset {
    //called when reset button is tapped
}

- (void)showResetButton {
    [UIView animateWithDuration:.3 animations:^{
        self.resetButton.alpha = 1.0;
    }];
}

- (void)hideResetButton {
    [UIView animateWithDuration:.3 animations:^{
        self.resetButton.alpha = 0.0;
    }];
}

答案 1 :(得分:0)

我不知道自己是否理解过,但是如果你想隐藏一个带有动作的对象,你可以这样做:

- (IBAction)myaction:(id)sender 
{
    self.object1.hidden = false ;
    self.object2.hidden = true ;
    self.object3.hidden = false ;   
}

答案 2 :(得分:0)

两种方式都很完美,我个人更喜欢Storyboard,因为它可以让您更轻松地安排按钮,并且在Interface Builder中添加自动布局(如果需要)的约束比在代码中更容易。

对于你的第二个问题:如果你的故事板混乱并且视图到处都是,我建议你从侧栏选择你的意见,而不是试图点击它们。此外,如果要移动所选视图,请在“工具”面板中调整坐标,而不是使用鼠标拖动它。

相关问题