如何从pickerInput中自动换行选择内容,如果选择内容的长度过长,则这些选择通常会最终出现在屏幕之外

时间:2018-07-16 06:37:37

标签: r shiny

pickerInput中的选择总是单行显示。有没有一种方法可以将它们带到下一行?当选择的长度过长而使选择不显示在屏幕上时,这是一个问题。我特别需要pickerInput,因为它具有实时搜索功能,可以选择全部/取消选择所有功能。

library("shiny")
library("shinyWidgets")
ui <- fluidPage(
  pickerInput(inputId="id",label="Some name",
    choices=c("Choice 1 is small","Choice 2 is average sized",
    "But choice 3 is very  big and sometimes when the length of the qption is long it leaves the screen, so I need a UI fix to wrap the question to fit the width of the pickerInput. I want pickerInput because it has select all/deselect all button."),
    selected=NULL,multiple=T,options=list(`actions-box`=TRUE,size=10,`selected-text-format`="count > 3")
  )
)
server <- function(input, output, session) {}
shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:4)

这里有两个解决方案,都使用choicesOpt参数来防止修改服务器端的值。

1。截断字符串以固定宽度

我使用了stringr::str_trunc

library("shiny")
library("shinyWidgets")

my_choices <- c(
  "Choice 1 is small","Choice 2 is average sized",
  "But choice 3 is very  big and sometimes when the length of the qption is long it leaves the screen, so I need a UI fix to wrap the question to fit the width of the pickerInput. I want pickerInput because it has select all/deselect all button."
)

ui <- fluidPage(

  pickerInput(
    inputId = "id",
    label = "Some name",
    choices = my_choices,
    selected = NULL,
    multiple = TRUE, 
    options = list(
      `actions-box` = TRUE, size = 10, `selected-text-format` = "count > 3"
    ),
    choicesOpt = list(
      content = stringr::str_trunc(my_choices, width = 75)
    )
  ),
  verbatimTextOutput(outputId = "res")
)

server <- function(input, output, session) {
  output$res <- renderPrint(input$id)
}

shinyApp(ui = ui, server = server)

enter image description here

2。插入换行符

我使用stringr::str_wrap将文本段落分成几行,然后用stringr::str_replace_all\n(HTML版本的<br>)替换\n

library("shiny")
library("shinyWidgets")

my_choices <- c(
  "Choice 1 is small","Choice 2 is average sized",
  "But choice 3 is very  big and sometimes when the length of the qption is long it leaves the screen, so I need a UI fix to wrap the question to fit the width of the pickerInput. I want pickerInput because it has select all/deselect all button."
)
my_choices2 <- stringr::str_wrap(my_choices, width = 80)
my_choices2 <- stringr::str_replace_all(my_choices2, "\\n", "<br>")

ui <- fluidPage(

  # tags$style(".text {width: 200px !important; word-break: break-all; word-wrap: break-word;}"),
  pickerInput(
    inputId = "id",
    label = "Some name",
    choices = my_choices,
    selected = NULL,
    multiple = TRUE, 
    options = list(
      `actions-box` = TRUE, size = 10, `selected-text-format` = "count > 3"
    ),
    choicesOpt = list(
      content = my_choices2
    )
  ),
  verbatimTextOutput(outputId = "res")
)

server <- function(input, output, session) {
  output$res <- renderPrint(input$id)
}

shinyApp(ui = ui, server = server)

enter image description here