2014-09-02 4 views
6

Есть ли эквивалент iOS для Android View.GONE?iOS эквивалентен View.GONE

В Android, установка вида GONE сделает его невидимым и обеспечит, чтобы представление не занимало места в макете. Я знаю, с прошивкой, вы можете установить вид на скрытые с

[viewName setHidden:true]; 

но вид по-прежнему занимает место в макете, и я думаю, что было бы неэффективно, чтобы полностью удалить представление и воссоздать его позже.

(примечание: я видел это сообщение: iOS equivalent for Android View.GONE visibility mode, но нет принятого ответа, а установка высоты на 0 не работала для меня, поскольку последующие виды на странице не сдвигались после удаления моего вида)

+0

Этот пост может дать вам представление. [LinkIsHere] (http://stackoverflow.com/questions/17869268/ios-equivalent-for-android-view-gone-visibility-mode) – TeachMeJava

ответ

4

возможно только эквивалент может быть AFAIK:

[yourView removeFromSuperview] 

пока вы не удалите view от своего superview в ios это займет место в макете.

Так что, в зависимости от вашей потребности, вы можете добавлять или удалять вид при необходимости (то же, что и view.GONE в android).

+0

спасибо за ваш ответ. Я попытался добавить это, но казалось, что представления ниже removeView не сдвинуты. Это что-то еще, что мне нужно включить? – scientiffic

+0

oky, чтобы сдвинуть вид вверх, вам нужно сдвинуть их вручную, или вы можете попробовать использовать функцию «Автоматическая компоновка». После удаления вашего вида; Измените положение 'view' под ним вверх, равное высоте снятого вида. Проверьте эту ссылку, чтобы переместить представление: 'http: // stackoverflow.com/questions/5161096/simple-way-to-change-the-position-of-uiview' – astuter

+0

https://stackoverflow.com/questions/45454992 –

2

В настоящее время я делаю переход между Android и iOS с помощью Swift, и это было одной из моих первых проблем. После поиска в Интернете я обнаружил, что некоторые люди имели хорошие результаты, установив высоту или ширину UIView равным 0, в зависимости от того, хотите ли вы, чтобы представление исчезло вертикально или горизонтально. Для реализации этой идеи в моем приложении я определил две функции:

enum Direction { 
    case HORIZONTAL, VERTICAL 
} 

func removeView(view: UIView, direction: Direction) { 
    // Removing the view vertically 
    if direction == .VERTICAL { 
     let constraint = NSLayoutConstraint(item: view as UIView, 
              attribute: NSLayoutAttribute.Height, 
              relatedBy: .Equal, 
              toItem: nil, 
              attribute: NSLayoutAttribute.NotAnAttribute, 
              multiplier: 0, 
              constant: 0) 
     view.addConstraint(constraint) 
    } else { // Removing the view horizontally 
     let constraint = NSLayoutConstraint(item: view as UIView, 
              attribute: NSLayoutAttribute.Width, 
              relatedBy: .Equal, 
              toItem: nil, 
              attribute: NSLayoutAttribute.NotAnAttribute, 
              multiplier: 0, 
              constant: 0) 
     view.addConstraint(constraint) 
    } 
} 

// Removing the view both horizontally and vertically 
func removeView(view: UIView) { 
    let constraintH = NSLayoutConstraint(item: view as UIView, 
              attribute: NSLayoutAttribute.Height, 
              relatedBy: .Equal, 
              toItem: nil, 
              attribute: NSLayoutAttribute.NotAnAttribute, 
              multiplier: 0, 
              constant: 0) 
    let constraintW = NSLayoutConstraint(item: view as UIView, 
              attribute: NSLayoutAttribute.Width, 
              relatedBy: .Equal, 
              toItem: nil, 
              attribute: NSLayoutAttribute.NotAnAttribute, 
              multiplier: 0, 
              constant: 0) 
    view.addConstraint(constraintH) 
    view.addConstraint(constraintW) 
} 

И, похоже, это работает на симуляторе. Надеюсь это поможет.

+0

https ://переполнение стека.com/questions/45454992 –

5

Добавьте ограничения ширины/высоты с constant = 0 до your View составит your View иметь ширину и высоту = 0 (как это GONE)

// set the height constraint to 0 
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:theGoneView 
                    attribute:NSLayoutAttributeHeight 
                    relatedBy:NSLayoutRelationEqual 
                     toItem:nil 
                    attribute:NSLayoutAttributeNotAnAttribute 
                    multiplier:1.0 
                    constant:0]]; 

// set the width constraint to 0    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:theGoneView 
                   attribute:NSLayoutAttributeWidth 
                   relatedBy:NSLayoutRelationEqual 
                    toItem:nil 
                   attribute:NSLayoutAttributeNotAnAttribute 
                   multiplier:1.0 
                   constant:0]]; 

В Swift

// set the width constraint to 0 
let widthConstraint = NSLayoutConstraint(item: theGoneView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0) 
view.addConstraint(widthConstraint) 

// set the height constraint to 0   
let heightConstraint = NSLayoutConstraint(item: theGoneView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0) 
    view.addConstraint(heightConstraint) 

Или это расширение UIView

extension UIView {   

    func goAway() { 
     // set the width constraint to 0 
     let widthConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 0) 
     superview!.addConstraint(widthConstraint) 

     // set the height constraint to 0 
     let heightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 0) 
     superview!.addConstraint(heightConstraint) 
    } 

} 

Надеюсь, что эта помощь

+1

Отличный ответ !!! btw «theGoneView» - это имя представления, которое нужно уйти. – Fay007

+0

@Phan Van Linh Я использовал тот же код, но он не работает ... https: //stackoverflow.com/questions/45454992/remove-white-space-after-hide-views-in-scrollview –

1

Самое чистое решение для меня заключается в том, чтобы вставлять компоненты, которые вы хотите «перемещать», в StackView (iOS 9.0+), а затем, вызывая UIView.isHidden = true на нужном представлении, вы достигаете именно вида. GONE эффект, потому что StackView обертывает контент.