UIPickerView重用视图始终为零

时间:2016-10-16 19:53:33

标签: ios swift uipickerview

根据Apples API引用重用此方法中的视图

public int AddEvent(string _title, string _description, string _place, int _eventTypeID, string _startingTime, string _endingTime, string _startingDate, string _endingDate, string _creatorID, string _picture)
{
    string[] blacklist = { _title, _description, _place, _picture };

    if (Jvalidate.FilterBlackLIstKeywords(blacklist))
    {
        int eventid = Convert.ToInt32(mydb.GetLastValueByColumnName("event_id", "tbl_events"));
        int rowsaffected = 0;
        mydb.CreateConnection();

        mydb.InitializeSQLCommandObject(mydb.GetCurrentConnection, "spAddEvent", true);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@eventID", eventid + 1);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@title", _title);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@description", _description);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@place", _place);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@eventType", _eventTypeID);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@startingTime", _startingTime);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@endingTime", _endingTime);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@startDate", _startingDate);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@endDate", _endingDate);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@schoolID", SchoolID);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@eventCreatorID", _creatorID);
        mydb.obj_sqlcommand.Parameters.AddWithValue("@eventPicture", _picture);
        try
        {
            //mydb.obj_sqlconnection.ConnectionString = ConfigurationManager.ConnectionStrings["cesConnectionString"].ToString();
            mydb.OpenConnection();
            rowsaffected = mydb.obj_sqlcommand.ExecuteNonQuery();
        }
        finally
        {
            mydb.CloseConnection();
            mydb.obj_sqlcommand.Dispose();
        }
        return rowsaffected;
    }
    return 0;
}

是一个由选择器视图提供的缓存视图,但是当我尝试将它用于下一行时,当我重新使用视图为零时,我返回optional func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView 时总是为零。问题是什么? 这是我的实施:

UILabel

1 个答案:

答案 0 :(得分:6)

您的代码不会尝试使用重用视图。你的代码应该是这样的:

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    var pickerLabel : UILabel
    if let label = view as? UILabel {
        pickerLabel = label
    } else {
        pickerLabel = UILabel()
        pickerLabel.textColor = UIColor.black
        pickerLabel.textAlignment = NSTextAlignment.center
    }

    pickerLabel.text = "10"
    pickerLabel.sizeToFit()

    return pickerLabel
}

如果重用视图是标签,则此代码重用标签。否则,它会创建并设置一个新标签。

请注意,选择器只会在滚动选择器视图时传入重用视图。它类似于表视图的单元重用。