我有两个文本的简单视图。其body
如下:
VStack {
Text("One")
Text("Two")
Text("Three")
}
这将产生如下视图:
但是我想要的是,仅使用Text
视图的修饰符(即不使用HStack
的{{1}}),实现如下布局:
这当前可行吗?我希望以某种方式使Spacer
的全宽,然后只使用文本对齐方式就可以了,但是还没有弄清楚。
答案 0 :(得分:2)
好吧...因为没有任何其他条件或限制,只添加了两行代码
预览中的演示(蓝色边框只是代码中的一个选择)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
nav_view = findViewById(R.id.nav_view);
nav_view.setNavigationItemSelectedListener(this);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
try {
Intent intent = getIntent();
if (intent.getStringExtra("activity").equals("register")) {
getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new UserprofileFragment()).commit();
}
} catch (NullPointerException noIntentExtra) {
getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new AssignmentsFragment()).commit();
}
if (mAuth.getCurrentUser() != null){
launchAssignmentFragment(); // launch the fragment maybe?
}
}
答案 1 :(得分:1)
是的,这有可能。您可以定义如下修饰符:
extension View {
func horizontalAlignment(_ alignment: HorizontalAlignment) -> some View {
Group {
if alignment == .leading {
HStack {
self
Spacer()
}
} else if alignment == .trailing {
HStack {
Spacer()
self
}
} else {
self
}
}
}
}
并像这样使用它:
VStack {
Text("One")
.horizontalAlignment(.leading)
Text("Two")
.horizontalAlignment(.center)
Text("Three")
.horizontalAlignment(.trailing)
}
当然,可以采用多种方法。
答案 2 :(得分:1)
一种方法是只设置框架:
struct ContentView: View {
var body: some View {
VStack {
Text("One")
.frame(minWidth: 0,
maxWidth: .infinity,
alignment: .leading)
Text("Two")
.frame(minWidth: 0,
maxWidth: .infinity,
alignment: .center)
Text("Three")
.frame(minWidth: 0,
maxWidth: .infinity,
alignment: .trailing)
}
}
}