在滚动视图Corona SDK中的文本框中居中显示文本

时间:2018-07-17 18:54:38

标签: lua scrollview corona

我正在为一个项目开发一个移动应用程序,但我遇到了麻烦。我没有实现滚动视图并在其中插入文本框和其他对象的问题,但是事实证明,将文本居中放在滚动视图中是一场噩梦。

我不确定还有其他选择,我想知道是否有人可以提供帮助。我已经附上了下面有关代码的一部分。

local widget = require( "widget" )

-- ScrollView listener
local function scrollListener( event )

local phase = event.phase
if ( phase == "began" ) then print( "Scroll view was touched" )
elseif ( phase == "moved" ) then print( "Scroll view was moved" )
elseif ( phase == "ended" ) then print( "Scroll view was released" )
end

-- In the event a scroll limit is reached...
if ( event.limitReached ) then
    if ( event.direction == "up" ) then print( "Reached bottom limit" )
    elseif ( event.direction == "down" ) then print( "Reached top limit" )
    elseif ( event.direction == "left" ) then print( "Reached right limit" )
    elseif ( event.direction == "right" ) then print( "Reached left limit" )
    end
end

return true
end

-- Create the widget
local scrollView = widget.newScrollView
{
    top = 50,
    left = 10,
    right = 10,
    width = 300,
    height = 388,
    scrollWidth = 600,
    scrollHeight = 800,
     topPadding = 120,
     bottomPadding = 50, 
     leftPadding = 50, 
     rightPadding = 50,
     horizontalScrollDisabled = true,
     verticalScrollDisabled = false,
    listener = scrollListener

}

local lotsOfText = "Ransomware is a form of malware. Malware (also known as 
malicious software) refers to a program that is created with the intent of 
causing harm, this damage could take a range of forms, from destructive (such 
as the deletion of files) to compromising the confidentiality or integrity of 
the victim’s data or system(s)." 

local options = {
text = lotsOfText,
x = display.contentCenterX,
y = 200,
fontSize = 16,
align = "center"
}

local lotsOfTextObject = display.newText( lotsOfText, 0, 0, 275, 0, "Arial", 
16)
lotsOfTextObject:setTextColor( 0, 0, 0 )
lotsOfTextObject.x = display.contentCenterX
lotsOfTextObject.y = display.contentCentery
scrollView:insert(lotsOfTextObject)

end

1 个答案:

答案 0 :(得分:0)

这里发生了一些事情。首先,我想指出的是,尽管您在选项中设置了x位置和文本居中对齐,但是您并未使用该表格,而是使用了旧式语法。 有关如何使用新语法的信息,请参见https://docs.coronalabs.com/api/library/display/newText.html#syntax

要使文本在滚动视图中居中,您要将x位置设置为滚动视图滚动宽度的一半。

local options = {
    text = lotsOfText,
    x = display.contentCenterX,
    y = 200,
    fontSize = 16,
    align = "center"
}
local lotsOfTextObject = display.newText(options)
lotsOfTextObject:setTextColor( 0, 0, 0 )

--The following sets your text to be in the middle of the scrollable area
lotsOfTextObject.x = 300 

--The following sets your text to be in the middle of the viewable area
lotsOfTextObject.x = scrollView.width / 2 

--The following sets your text to be at the top of the viewable area
lotsOfTextObject.y = 0
lotsOfTextObject.anchorY = 0

scrollView:insert(lotsOfTextObject)