2015-09-09 2 views
0

Я сталкиваюсь с проблемой с относительной компоновкой. Моя цель создать подобное расположение: enter image description hereXamarin.Forms Относительное расположение странное поведение

Отказ от ответственности: Это должно быть относительная раскладка только потому, что мне нужно добавить некоторые другие элементы, которые позиция зависит от этого два.

Это мой код:

var layout = new RelativeLayout(); 

var box = new BoxView { BackgroundColor = Color.Olive, WidthRequest = 50, HeightRequest = 50 }; 

var label = new Label 
{ 
    LineBreakMode = LineBreakMode.WordWrap, 
    Text = "Here is a lot of text ..... Here is a lot of text"; 
}; 
layout.Children.Add(box, Constraint.Constant(10), Constraint.Constant(10)); 
layout.Children.Add(label, 
    Constraint.RelativeToView(box, (relativeLayout, view) => view.X + view.Width + 20), 
    Constraint.RelativeToView(box, (relativeLayout, view) => view.Y), 
    //Constraint.RelativeToParent(relativeLayout => relativeLayout.Width - 20 - 50 -10)); 


MainPage = new ContentPage 
{ 
    Content = layout  
}; 

Вот моя проблема. Если я не добавляю прокомментированную строку, тогда ярлык выходит из экрана. Как и здесь: enter image description here

Если я добавляю прокомментированную строку (которая является ограничением ширины), то возникает еще одна странная вещь: текст не отображается полностью. Я имею в виду, что должно быть еще 10 слов, но они внезапно исчезают. enter image description here

Я не установлены Рост ограничений, так что не должны ограничивают размер этикетки.

Не могли бы вы помочь мне в этом? Спасибо!

ответ

1
  • Убедитесь, что вы устанавливаете RelativeLayout HorizontalOptions и VerticalOptions, чтобы заполнить экран
  • Вычислить ярлык X Constraint правильно view.X + view.Width + 20 ->view.X + view.Width + 10
  • Высота этикетки неверен потому, что вы не установили его. Когда вы используете AbsoluteLayout или RelativeLayout, вы ДОЛЖНЫ устанавливать размеры своих детей вручную. Так оно и есть.

Здесь работает пример:

var layout = new RelativeLayout() { 
     HorizontalOptions = LayoutOptions.FillAndExpand, 
     VerticalOptions = LayoutOptions.FillAndExpand 
    }; 

    const double boxSize = 50; 
    const double margin = 10; 

    var box = new BoxView { 
     BackgroundColor = Color.Olive, 
     WidthRequest = boxSize, 
     HeightRequest = boxSize 
    }; 

    var label = new Label { 
     LineBreakMode = LineBreakMode.WordWrap, 
     Text = "Cras efficitur, sem a scelerisque pretium, leo turpis cursus lacus, id consequat erat risus sit amet tortor. Nullam fringilla vestibulum mauris, vel fringilla lectus molestie eget. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent quis elit eu nulla varius consectetur. Ut eleifend odio at malesuada lacinia. Fusce neque orci, efficitur nec condimentum et, volutpat id odio. Quisque vel metus vitae lectus vulputate placerat. Aliquam erat volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec suscipit, ipsum nec tincidunt porta, enim lacus consequat magna, nec scelerisque lacus lacus luctus mi. Proin rutrum luctus libero, sed lacinia tellus. Nunc dapibus arcu dui, quis bibendum elit interdum sit amet. Vivamus sed consequat mi. Aliquam sagittis ante ac massa bibendum, eu pharetra diam malesuada. Duis maximus magna id lorem lacinia, sed consectetur quam sagittis. Fusce at pulvinar ex." 
    }; 
    layout.Children.Add(box, Constraint.Constant(margin), Constraint.Constant(margin)); 

    layout.Children.Add(label, 
     Constraint.RelativeToView(box, (relativeLayout, view) => view.X + boxSize + margin), 
     Constraint.RelativeToView(box, (relativeLayout, view) => view.Y), 
     Constraint.RelativeToParent((relativeLayout) => relativeLayout.Width - boxSize - margin * 3), 
     Constraint.RelativeToParent((relativeLayout) => relativeLayout.Height * 0.8f)); // eg. 80% of its parent 
+0

Хм .. Пробовал ваше решение и обнаружил, что у него такая же проблема. Слова с конца просто исчезают. См. [Мой экран] (http://imgur.com/AHkjZFf). Он должен заканчиваться _Fusce на pulvinar ex._, но заканчивается чем-то другим. –

+0

Какова ваша тестовая платформа? Android? –

+0

Я запускаю его как на iOS, так и на Android. –

0

Там ничто не мешает вам используя расположение стека в пределах вашего относительного расположения.

E.g.

var stackLayout = new StackLayout { 
    Orientation = StackOrientation.Horizontal, 
    Padding = new Thickness (20, 10, 10, 0), 
    Children = { 
     new BoxView { 
      BackgroundColor = Color.Olive, 
      WidthRequest = 50, 
      HeightRequest = 50, 
      HorizontalOptions = LayoutOptions.Start, 
      VerticalOptions = LayoutOptions.Start 
     }, 
     new Label { 
      LineBreakMode = LineBreakMode.WordWrap, 
      HorizontalOptions = LayoutOptions.FillAndExpand, 
      Text = "Here is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of textHere is a lot of text ..... Here is a lot of text" 
     } 
    } 
}; 

var relLayout = new RelativeLayout(); 
relLayout.Children.Add (stackLayout, 
    Constraint.Constant (0), 
    Constraint.Constant (0), 
    Constraint.RelativeToParent((p)=>{return p.Width;}), 
    Constraint.RelativeToParent((p)=>{return p.Height;}) 
); 

Конечно, вам нужно будет возиться со значениями, но основное помещение есть.

Смежные вопросы